I am trying to bind a XML page to same underlying code page.
<toolkit:ToggleSwitch Foreground="Transparent" Checked="ToggleSwitch_Checked" IsChecked="{Binding Source={StaticResource appSettings}, Path=LockSetting, Mode=TwoWay}">
<toolkit:ToggleSwitch.ContentTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" DataContext="{Binding}">
<TextBlock Text="locks or unlocks your calender" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="statusBox" Text="{Binding stat1}" Style="{StaticResource PhoneTextTitle3Style}" />
</StackPanel>
</DataTemplate>
</toolkit:ToggleSwitch.ContentTemplate>
I have set the data context as
stat1 = "abn";
InitializeComponent();
aps = this.Resources["appSettings"] as AppSettings;
this.colorpicker.Color = Color.FromArgb(aps.ASetting, aps.RSetting, aps.GSetting, aps.BSetting);
ContentPanel.DataContext = this;
But this is not working at all. Any help will be good.
When you write ContentPanel.DataContext = this it implies in this case that the Code-behind of the XAML would be providing context for the data binding. More specifically, when you write {Binding sta1} in the XAML, sta1 must be a property in the code behind. That is, sta1 should be something like that:
public String sta1 { get; set; }
Related
I'm trying to bind a list to a listbox in WPF. But it doesn't seem to work, I just see nothing on screen.
Here is my code:
WPF
<ListBox x:Name="listBox" HorizontalAlignment="Left" Height="453" VerticalAlignment="Top" Width="119" Margin="0,43,0,0" ItemsSource="{Binding orderlist}">
<ListBoxItem Content="{Binding orderlist.ID}"></ListBoxItem>
</ListBox>
C#
Order order = new Order();
Klantgegevens klantgegevens = new Klantgegevens();
XmlReader rdr = XmlReader.Create(#"C:\Users\Gebruiker\Desktop\EDI\Rekening.xml");
rdr.ReadToFollowing("datum");
order.DatumOntvangst = rdr.ReadElementContentAsString();
rdr.ReadToFollowing("volgnr");
order.Status = "Aangenomen";
order.Opmerkingen = "";
rdr.ReadToFollowing("naam");
order.Afzender = rdr.ReadElementContentAsString();
rdr.ReadToFollowing("naam");
klantgegevens.Naam = rdr.ReadElementContentAsString();
rdr.ReadToFollowing("straat");
klantgegevens.Straat = rdr.ReadElementContentAsString();
rdr.ReadToFollowing("huisnr");
klantgegevens.Huisnummer = rdr.ReadElementContentAsInt();
rdr.ReadToFollowing("plaats");
klantgegevens.Woonplaats = rdr.ReadElementContentAsString();
rdr.ReadToFollowing("postcode");
klantgegevens.Postcode = rdr.ReadElementContentAsString();
rdr.ReadToFollowing("telefoonnr");
klantgegevens.Telefoonnummer = rdr.ReadElementContentAsString();
order.Klantgegevens = klantgegevens;
orderlist.Add(order);
listBox.DataContext = orderlist;
As you probably know, Order is a custom class, and so is Klantgegevens.
I'm pretty new to binding and WPF in general so excuse me for my stupidness :)
You need to set or bind the ItemsSource property of ListView to an IEnumerable. Since you have set the DataContext property to your "orderlist" you should bind the ItemsSource property directly to the DataContext (ItemsSource="{Binding}"). You should also use an ItemTemplate as suggested by Fruchtzwerg :
<ListBox x:Name="listBox" HorizontalAlignment="Left" Height="453" VerticalAlignment="Top" Width="119" Margin="0,43,0,0" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ID}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Also note that the DataContext of the ItemTemplate is an item in your ItemsSource, i.e. an Order object in this case. So to bind to the "ID" property of the Order object you use the binding syntax above. "ID" must be a public property of the Order class.
With
<ListBoxItem Content="{Binding orderlist.ID}"></ListBoxItem>
you are adding an item in XAML. But your plan is to create a template to present bound items. The simplest solution is to use
<ListBox x:Name="listBox" DisplayMemberPath="ID"/>
if only one property needs to be presented. Multiple properties can be showed by creating a template like
<ListView x:Name="listBox">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding ID}" />
<TextBlock Text="{Binding datum}"/>
<!-- ... -->
</WrapPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Furthermore you should use a property like
public ObservableCollection<Klantgegevens> Items { get; } =
new ObservableCollection<Klantgegevens>();
to bind on. Set the DataContext of the whole Window with the ListView to the object, with this property. After that you can bind the ListView with
<ListView ItemsSource="{Binding Items}"/>
I have a ListBox element,
which purpose is to show the users the activities,
that are registered on the Database
so that they can choose from them to modify or delete them.
After consulting two very useful answers about using DataContext and DataTemplates,
I decided to implement that knowledge in my project,
unfortunately, it's not working.
When I run it and I select the text on the ListBox,
I only see: DataTemplate templ = new DataTemplate(typeof(Activities));
as its content, and I didn't mark it up as code,
because I want to stress the fact that it appears as a string,
if you will.
I get that there could be more than one workaround for what I'm trying to achieve.
however I really want to understand this, as it appears to be very useful.
Here's the code:
//This is the connection instance to the database
Connection c = new Connection();
DataTemplate templ = new DataTemplate(
typeof(Activities)
);
//The ListActivities method returns
//an ObservableCollection<Activities> list
libTest.DataContext = c.ListActivities(
objSem.getId()
);
libTest.SetBinding(
ItemsControl.ItemsSourceProperty, new Binding()
);
FrameworkElementFactory sp = new FrameworkElementFactory(
typeof(StackPanel)
);
sp.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
sp.Name = "myTemplate";
FrameworkElementFactory date = new FrameworkElementFactory(
typeof(Label)
);
date.SetBinding(Label.ContentProperty, new Binding("date"));
sp.AppendChild(date);
FrameworkElementFactory nameAct = new FrameworkElementFactory(
typeof(Label)
);
nameAct.SetBinding(Label.ContentProperty, new Binding("nameAct"));
sp.AppendChild(nameAct);
FrameworkElementFactory descr = new FrameworkElementFactory(
typeof(Label)
);
descr.SetBinding(Label.ContentProperty, new Binding("descr"));
sp.AppendChild(descr);
FrameworkElementFactory quantity = new FrameworkElementFactory(typeof(Label));
quantity.SetBinding(Label.ContentProperty, new Binding("quantity"));
sp.AppendChild(quantity);
templ.VisualTree = sp;
libTest.ItemTemplate = templ;
i dont like code definition for such thing so here is the xaml one
<DataTemplate DataType="{x:Type local:Activities}">
<StackPanel Orientation="Horizontal">
<Label Content="{Binding date}"/>
<Label Content="{Binding nameAct}"/>
<Label Content="{Binding descr}"/>
<Label Content="{Binding quantity}"/>
</StackPanel>
</DataTemplate>
just put this into your resources and all Activities will render like this
pls read something more about binding in WPF, maybe MVVM stuff too. so you would better understand what you need when you do binding with WPF.
a little example
create a class which will be your DataContext and put a public property for your List in it.
public class SampleViewModel
{
public ObservableCollection<Activities> MyActivities {get;set;}
}
xaml.cs: set the DataContext for your View to your Viewmodel class
public partial class SampleWindow : Window
{
private SampleViewModel _data;
public SampleWindow()
{
_data = new SampleViewModel();
InitializeComponent();
this.DataContext = _data;
}
}
xaml: define your Bindings for your controls
<ListBox ItemsSource="{Binding MyActivities}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Label Content="{Binding date}"/>
<Label Content="{Binding nameAct}"/>
<Label Content="{Binding descr}"/>
<Label Content="{Binding quantity}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
or
<ListBox ItemsSource="{Binding MyActivities}">
<ListBox.Resources>
<DataTemplate DataType="{x:Type local:Activities}">
<StackPanel Orientation="Horizontal">
<Label Content="{Binding date}"/>
<Label Content="{Binding nameAct}"/>
<Label Content="{Binding descr}"/>
<Label Content="{Binding quantity}"/>
</StackPanel>
</DataTemplate>
</ListBox.Resources>
</ListBox>
I'm about to make a control page that has several textblock.
each textblock will be "linked" to another page,
here's my xaml part
.........<phone:LongListSelector x:Name="settingSelector" ItemsSource="{Binding}">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel toolkit:TiltEffect.IsTiltEnabled="True" Tap="{Binding TapMethod, Mode=TwoWay}" >
<TextBlock Text="{Binding SetTitle}" FontSize="43" />
<TextBlock Text="{Binding SetDescription}" FontSize="19" Margin="0 0 0 10" />
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>..........
when I try this code behind :
.........public class SettingProperty
{
public string SetTitle{get; set;}
public string SetDescription{get; set;}
public string TapMethod{get; set;}
public SettingProperty(string setTitle, string setDescription, string tapMethod)
{
SetTitle = setTitle;
SetDescription = setDescription;
TapMethod = tapMethod;
}
}
List<SettingProperty> DataSetting()
{
List<SettingProperty> settingCollection = new List<SettingProperty>();
settingCollection.Add(new SettingProperty("Saldo", "cek saldo", "saldo_Tap"));
return settingCollection;
}
private void saldo_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
NavigationService.Navigate(new Uri("/saldo.xaml", UriKind.Relative));
}..........
I directly deployed them to my L520, I'm prety sure the culprit is the "Tap" binding on my stackpanel, when I omit it, the code works.
Did I miss something, or my whole method is just wrong?
our understanding of the "Tap" event is wrong.
You have two options here:
Either you clearly specify a METHOD NAME (not a string) as a event handler for the Tap event. For example:
Tap="MyControl_Tap"
In this case you must have a MyControl_Tap method in your control's code behind
OR, since you seem to be using the MVVM pattern, you have to create a ICommand, and then include your whole StackPanel in a Button, like this:
...<DataTemplate>
<Button Command="{Binding MyCommandProperty}">
<StackPanel toolkit:TiltEffect.IsTiltEnabled="True" >
<TextBlock Text="{Binding SetTitle}" FontSize="43" />
<TextBlock Text="{Binding SetDescription}" FontSize="19" Margin="0 0 0 10" />
</StackPanel>
</Button>
...
I am sharing the screen shot of my application. The image which is coming i want it to be in the side and should be small in size. Here i am not getting the full image also. Can anyone help me to fit the image in the listbox and appear it in the side.
My xaml code is:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox Name="listBox1">
<ListBox.ItemTemplate>
<DataTemplate>
<Button>
<Button.Content>
<ScrollViewer HorizontalScrollBarVisibility="Auto" Height="80" Width="400">
<!--<ScrollViewer Height="80">-->
<StackPanel Orientation="Horizontal" Margin="0,0,0,0">
<StackPanel Orientation="Vertical" Height="80">
<TextBlock Text="{Binding Path=News_Title}" TextWrapping="Wrap" ></TextBlock>
<TextBlock Text="{Binding Path=News_Description}" TextWrapping="Wrap"></TextBlock>
<TextBlock Text="{Binding Path=Date_Start}" TextWrapping="Wrap"></TextBlock>
<Image Source="{Binding ImageBind }" />
</StackPanel>
</StackPanel>
</ScrollViewer>
</Button.Content>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
My .cs code is:
public class Newss
{
public string News_Title { get; set; }
public string News_Description { get; set; }
public string Date_Start { get; set; }
public string image_path { get; set; }
public BitmapImage ImageBind{get;set;}
}
public News()
{
InitializeComponent();
KejriwalService.aapSoapClient client = new KejriwalService.aapSoapClient();
client.getarvindNewsCompleted += new EventHandler<KejriwalService.getarvindNewsCompletedEventArgs>(client_getarvindNewsCompleted);
client.getarvindNewsAsync();
}
void client_getarvindNewsCompleted(object sender, KejriwalService.getarvindNewsCompletedEventArgs e)
{
string result = e.Result.ToString();
List<Newss> listData = new List<Newss>();
XDocument doc = XDocument.Parse(result);
foreach (var location in doc.Descendants("UserDetails"))
{
Newss data = new Newss();
data.News_Title = location.Element("News_Title").Value;
//data.News_Description = location.Element("News_Description").Value;
data.Date_Start = location.Element("Date_Start").Value;
data.image_path = location.Element("image_path").Value;
data.ImageBind = new BitmapImage(new Uri( #"http://political-leader.vzons.com/ArvindKejriwal/images/uploaded/"+data.image_path, UriKind.Absolute));
listData.Add(data);
}
listBox1.ItemsSource = listData;
}
Try to move your Image outside inner StackPanel :
.....
<StackPanel Orientation="Horizontal" Margin="0,0,0,0">
<StackPanel Orientation="Vertical" Height="80">
<TextBlock Text="{Binding Path=News_Title}" TextWrapping="Wrap" ></TextBlock>
<TextBlock Text="{Binding Path=News_Description}" TextWrapping="Wrap"></TextBlock>
<TextBlock Text="{Binding Path=Date_Start}" TextWrapping="Wrap"></TextBlock>
</StackPanel>
<Image Source="{Binding ImageBind }" />
</StackPanel>
.....
That will make the Image appear besides the Text. Then try to set Width and Height properties of Image control to fixed value, and set Stretch property appropriately. See this post for reference about setting Stretch property.
There're too many wrong things here, and I don't know what you want.
You've put buttons inside items of ListBox. You should either remove buttons and rely on listbox own items selection mechanism for handling touch elents, or continue using buttons but replace ListBox with ItemsControl that doesn’t handle touch.
You’ve put ScrollViewer inside those buttons. So if you have 10 items, you’ll have 10 buttons, each with its own scroll viewer. Why you did that?
You’ve set height of your StackPanel to 80. When specifying fixed height, Silverlight often does not care whether the content fits or no, instead it clips things. It’s rarely a good idea to specify absolute size of elements.
Instead of using two nested stack panels, you should use single Grid with two rows and two columns, where image occupies both rows of the second column (using Grid.RowSpan property).
And you’re asking question about changing image style? You should fix the rest of your XAML first…
I cannot find any examples to make me understand how and if I can change the databind in c# at the click of a button on, in my case a toggleswitch, Basically I have 32 buttons in my app and those 32 buttons act the same but need different text with-in them depending on some toggle switches they are currently databinded so the text can be saved and retrieved from local storage but what values it gets depends on the state of these toggle switches.
So I currently have :
<Button x:Name="_ovButton1" Content="{Binding Source={StaticResource AppSettings}, Path=ovName1_1Value, Mode=TwoWay}" Margin="2,0,250,0" VerticalAlignment="Top" FontSize="14" Height="72" FontWeight="Bold" MouseLeftButtonUp="_ovButton1_MouseLeftButtonUp" MouseLeftButtonDown="_ovButton1_MouseLeftButtonDown" ClickMode="Hover" Hold="_ovButton1_Hold"/>
and I want when a user changes the state of a toggleswitch to change the
{StaticResource AppSettings}, Path=ovName1_1Value, Mode=TwoWay}
to for example:
{StaticResource AppSettings}, Path=ovName1_2Value, Mode=TwoWay}
but I cannot find any example that shows how to do that in c#
what code do I need to do that?
You can specify the target of databinding in code like this:
MyData myDataObject = new MyData(DateTime.Now);
Binding myBinding = new Binding("MyDataProperty");
myBinding.Source = myDataObject;
myText.SetBinding(TextBlock.TextProperty, myBinding);
See more at http://msdn.microsoft.com/en-us/library/ms742863.aspx
-- Edit Note I don't have access to a WP8 Emulator to test this ---
In the view model it looks like this:
public List<string> Members
{
get { return _Members; }
set { _Members = value; OnPropertyChanged(); }
}
public MainVM()
{
// Simulate Asychronous access, such as to a db.
Task.Run(() =>
{
Thread.Sleep(2000);
Members = new List<string>() {"Alpha", "Beta", "Gamma", "Omega"};
});
}
The code behind on the main page sets the datacontext (shared with all the child controls) as such:
public MainWindow()
{
InitializeComponent();
// Set the windows data context so all controls can have it.
DataContext = new MainVM();
}
The Mainpage Xaml to bind to members is like this
<Button Height="30"
Width="80"
Margin="10"
DataContext="{Binding Members}"
Content="{Binding Path=[0] }" />
<Button Height="30"
Width="80"
Margin="10"
DataContext="{Binding Members}"
Content="{Binding Path=[1] }" />
<Button Height="30"
Width="80"
Margin="10"
DataContext="{Binding Members}"
Content="{Binding Path=[2] }" />
<Button Height="30"
Width="80"
Margin="10"
DataContext="{Binding Members}"
Content="{Binding Path=[3] }" />
The result is this visually:
I based this on my blog article Xaml: ViewModel Main Page Instantiation and Loading Strategy for Easier Binding for more info and a fuller example.
I think your best bet is going to be to use a collection of strings and bind to that collection. You can either change the collection when a toggle is switched, or keep 6 collections and bind to the collection that is for the toggle.
Xaml:
<ItemsControl x:Name="Buttons" ItemsSource="{Binding ButtonTextCollection}">
<ItemsControl.ItemsPanel>
<toolkit:WrapPanel/>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Width="100" Height="70" Content="{Binding}" Click="OnButtonClick"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Your code-behind would have the event handler for your button click
private void OnButtonClick(object sender, RoutedEventArgs e)
{
var text = ((Button) sender).Content.ToString();
// Send the text
}
Your ViewModel would hold the ButtonTextCollection property and would change based on the toggle.
public ICollection<string> ButtonTextCollection
{
get { return _buttonTextCollection; }
set
{
_buttonTextCollection = value;
OnPropertyChanged("ButtonTextCollection");
}
}
When you want to change the text, you would change the ButtonTextCollection
public void ChangeButtonText()
{
ButtonTextCollection = new Collection<string> {"A", "B",...};
}