I'm fairly new to XAML but enjoying learning it. The thing I'm really struggling with is binding a property to an element in a DataTemplate.
I have created a simple WPF example to, (hopefully,) explain my problem.
I this example I am trying to bind the Visibility property of a CheckBox in a DataTemplate to a Property in my viewmodel. (Using this scenario purely for learning/demo.)
I have a simple DataModel named Item, but is of little relevance in this example.
class Item : INotifyPropertyChanged
{
// Fields...
private bool _IsRequired;
private string _ItemName;
And a fairly simple View Model named ItemViewModel.
class ItemViewModel : INotifyPropertyChanged
{
private ObservableCollection<Item> _Items;
private bool _IsCheckBoxChecked;
private bool _IsCheckBoxVisible;
public ObservableCollection<Item> Items
{
get { return _Items; }
set { _Items = value; }
}
public bool IsCheckBoxChecked
{
get { return _IsCheckBoxChecked; }
set
{
if (_IsCheckBoxChecked == value)
return;
_IsCheckBoxChecked = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("IsCheckBoxChecked"));
PropertyChanged(this, new PropertyChangedEventArgs("IsCheckBoxVisible"));
}
}
}
public bool IsCheckBoxVisible
{
get { return !_IsCheckBoxChecked; }
set
{
if (_IsCheckBoxVisible == value)
return;
_IsCheckBoxVisible = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("IsCheckBoxVisible"));
}
(Constructors and INotifyPropertyChanged implementation omitted for brevity.)
Controls laid out in MainPage.xaml as follows.
<Window.Resources>
<local:VisibilityConverter x:Key="VisibilityConverter"/>
</Window.Resources>
<Window.DataContext>
<local:ItemViewModel/>
</Window.DataContext>
<Grid>
<StackPanel>
<CheckBox x:Name="checkBox" Content="Hide CheckBoxes" FontSize="14" IsChecked="{Binding IsCheckBoxChecked, Mode=TwoWay}" />
<ListView ItemsSource="{Binding Items}" HorizontalContentAlignment="Stretch" >
<ListView.ItemTemplate >
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding ItemName}"/>
<CheckBox Grid.Column="1" Visibility="{Binding IsCheckBoxVisible, Converter={StaticResource VisibilityConverter}}" >
<CheckBox.DataContext>
<local:ItemViewModel/>
</CheckBox.DataContext>
</CheckBox>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<StackPanel Orientation="Horizontal" Margin="4,4,0,0">
<TextBlock Text="IsCheckBoxVisible:"/>
<TextBlock Text="{Binding IsCheckBoxVisible}" Margin="4,0,0,0" FontWeight="Bold" />
</StackPanel >
<Button Content="Button" Visibility="{Binding IsCheckBoxVisible, Converter={StaticResource VisibilityConverter}}" Margin="4,4,4,4"/>
</StackPanel>
</Grid>
The 'Hide CheckBoxes' checkbox is bound to IsCheckBoxChecked and is used to update IsCheckBoxVisible. I've also added a couple of extra controls below the DataTemplate to prove, (to myself,) the everything works.)
I have also implemented Jeff Wilcox's value converter. (Thank you.) http://www.jeff.wilcox.name/2008/07/visibility-type-converter/
When I run the app, checking and unchecking the 'Hide Checkbox', controls outside the DataTemplate function as expected but, alas, the Checkbox inside the data template remains unchanged.
I have had success with:
IsVisible="{Binding IsChecked, Converter={StaticResource VisibilityConverter}, ElementName=checkBox}"
But I'm not just trying mimic another control but make decisions based on a value.
I would REALLY appreciate any help or advice you can offer.
Thank you.
When you are in a DataTemplate, your DataContext is the data templated object, in this case an Item. Thus, the DataContext of the CheckBox in the DataTemplate is an Item, not your ItemViewModel. You can see this by your <TextBlock Text="{Binding ItemName}"/>, which binds to a property on the Item class. The Binding to IsCheckBoxVisible is trying to find a property called IsCheckBoxVisible on Item.
There are a couple of ways around this, but by far the easiest is to do this:
On your Window (in the xaml), give it and x:Name. Eg:
<Window [...blah blah...]
x:Name="MyWindow">
Change your binding to look like this:
<CheckBox Grid.Column="1"
Visibility="{Binding DataContext.IsCheckBoxVisible, ElementName=MyWindow, Converter={StaticResource VisibilityConverter}}">
We're using the Window as the source for the Binding, then looking at its DataContext property (which should be your ItemViewModel, and then pulling off the IsCheckBoxVisible property.
Another option, if you want something fancier, is to use a proxy object to reference your DataContext. See this article on DataContextProxy.
Related
I'm trying to create a new window (child of MainWindow) that will display different numbers of rows with data each time. I used the following template that I copied from a wpf template tutorial. I've checked that the data are right and I can project them right with a MessageBox.Show window but I can't make them appear as bound properties. Here is the xaml...
<ListView x:Name="listUnits" x:FieldModifier="public" HorizontalAlignment="Left" Height="Auto" Margin="5,5,5,5" VerticalAlignment="Top" Width="Auto">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Id:"/>
<TextBlock Text="{Binding pu_Id}" Width="Auto"/>
<TextBlock Text=" "/>
<TextBlock Text="{Binding pu_unitName}" Width="Auto"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
So although pu_unitName contains the data, they're are displayed in the new window.
The binding is done in the constructor:
public partial class ChooseUnit : Window
{
public ChooseUnit(List<XML_Handler.PrUnits> thisList)
{
InitializeComponent();
listUnits.ItemsSource = thisList;
}
}
The PrUnits is a class which contains variables including pu_id and pu_unitName. So what's wrong with this code?
Since you can only bind to public properties, you need to make sure that pu_Id and pu_UnitName are properties (and not fields) of the PrUnits class. Then your bindings will work.
Also note that this is not a binding:
listUnits.ItemsSource = thisList;
In general, you would set the DataContext of the parent window to an instance of a view model class and bind the ItemsSource property of the ListView to a property that returns the List<XML_Handler.PrUnits>:
<ListView x:Name="listUnits" ItemsSource="{Binding Units}">
...
In your .cs:
public partial class ChooseUnit : Window
{
public ChooseUnit(List<XML_Handler.PrUnits> thisList)
{
InitializeComponent();
this.DataContext = thisList;
}
}
What this does it assigns the data context of your window to the list of itemsa you are trying to pass. At this point every element in that window will have access to the passed in list.
And then in your XAML do this:
<ListView x:Name="listUnits" ItemsSource="{Binding .}" x:FieldModifier="public" HorizontalAlignment="Left" Height="Auto" Margin="5,5,5,5" VerticalAlignment="Top" Width="Auto">
This allows us to use binding as the entire window has access to the list. Hence ItemsSource="{Binding .}".
EDIT
Reading more into your question and thanks to Ash your class needs to expose Properties with INotifyPropertyChanged interface implemented.
This interface is expected by the WPF framework so it can subscribe to the changed events and update the UI.
Im having some problems with setting up databinding in Silverlight.
Im trying to use the MVVM approach and found some nice examples, So Ive created my View and my ViewModel, I created some classes Im going to use to contain the data and one to populate the classes.
Firstly my ViewModel looks like:
public class MainPageVM : INotifyPropertyChanged
{
ObservableCollection<Item> Items;
public MainPageVM()
{
InitializeItems InitItems = new InitializeItems();
InitItems.GenerateItemList(out Items);
RaiseProertyChanged("Items");
}
public string test = "Binding Test";
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
private void RaiseProertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
And then in my View i have :
<UserControl.Resources>
<viewmodel:MainPageVM x:Key="ViewModel" />
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White" DataContext="{StaticResource ViewModel}">
<StackPanel>
<TextBlock Text="{Binding test}"/>
<ListBox ItemsSource="{Binding Items}"
Width="200"
Height="200">
<ListBoxItem Width="190" Height="20">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding ItemName}"/>
<TextBlock Text="-"/>
<TextBlock Text="{Binding ItemID}"/>
</StackPanel>
</ListBoxItem>
</ListBox>
</StackPanel>
</Grid>
I added breakpoints and I know my ObservableCollection that im trying to bind to is being populated but nothing binds, in the error window im just getting xxx property doesnt exist in MainPageVM.
Any advice here would be great as im a bit lost as to what could be going on, and this is my first silverlight application.
Thanks
Items needs to be a public property. Same with your test field. In Silverlight you can only bind to public properties.
Also, typically in the Setter of those properties you raise the property changed event. This tells the Silverlight runtime to refresh the controls that are bound to that property with the new values of that property.
I was trying to figure this out for quite some time.I want a Databind a listbox with a Dataset.Simple as it can get.But my problem is that i want my datatemplate to display Columns from two tables,in the dataset.I have tried many samles..but everything i found just gives the dataset as datacontext and gives a single table as itemsource.But my condition is that i want more than one table in my datatemplate..
For eg:
<DataTemplate x:Key="EmployeeDataTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="60"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Margin="5" BorderBrush="Black" BorderThickness="1">
<Image Source="{Binding Path=Mast/Image}" Stretch="Fill" Width="50" Height="50" />
</Border>
<StackPanel Grid.Column="1" Margin="5">
<StackPanel Orientation="Horizontal" TextBlock.FontWeight="Bold" >
<TextBlock Text="{Binding Path=Mast/Firstname}" />
<TextBlock Text="{Binding Path=Mast/Lastname}" Padding="3,0,0,0"/>
</StackPanel>
<TextBlock Text="{Binding Path=Details/Age}" />
<TextBlock Text="{Binding Path=Details/Role}" />
</StackPanel>
</Grid>
</DataTemplate>
Any way to do this..? I am confused...!
I tried giving the Dataset as datacontext and Itemsource as {Binding} But only one row is displayed...
You should create a view model class that exposes three properties:
MasterTable of type IEnumerable<MasterTableRow>
SelectedMaster of type DataRowView
MasterDetails of type IEnumerable<DetailsTableRow>
In your view model, put your instance of your DataSet, and return the appropriate values for the properties. To wrap it all up, you should implement INotifyPropertyChanged and fire change notifications for SelectedMaster and MasterDetails whenever SelectedMaster changes.
Remember to set the view model as the DataContext for the bindings.
Here's how it might look like:
public partial class ViewModel : INotifyPropertyChanged
{
DataSet1 ds;
DataRowView selectedMaster;
public IEnumerable<DataSet1.MasterTableRow> MasterTable
{
get { return ds.MasterTable; }
}
public DataRowView SelectedMaster
{
get { return selectedMaster; }
set
{
if (selectedMaster != value)
{
selectedMaster = value;
OnPropertyChanged("MasterDetails");
OnPropertyChanged("SelectedMaster");
}
}
}
public IEnumerable<DataSet1.DetailsTableRow> MasterDetails
{
get
{
var masterRow = (DataSet1.MasterTableRow)SelectedMaster.Row;
return masterRow.GetDetailsTableRows();
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string prop)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
#endregion
}
In XAML, the bindings might look like this:
<ListBox ItemsSource="{Binding MasterTable}"
SelectedItem="{Binding SelectedMaster}"
ItemTemplate="{StaticResource MasterTemplate}"/>
<ListBox ItemsSource="{Binding MasterDetails}"
ItemTemplate="{StaticResource DetailsTemplate}"/>
This is a long one . I am adding code so that you can see what I am trying to do. Let me know if anything is not clear
I am trying to get selected items from nested listbox in multiselct mode . Here is code ( removed lot of unwanted stuff)
public class Item
{
public string Name { get; set; }
public IList<Item> SubItems { get; set; } //
public bool IsSelected { get; set; }
}
//Chicken Fried Chicken
//A hearty boneless chicken breast, lightly breaded in our special seasonings and
//golden fried. Served with garlic mashed potatoes, country gravy and seasonal vegetables
// from Applebees
//Item - Chicken Fried Chicken
//SubItem- mashed potatoes
//SubItem- country gravy
//SubItem- seasonal vegetables
//SubItem- Fries
//SubItem- Sauted vegetables
//SubItem- House Salad
public class ItemViewModel : INotifyPropertyChanged, IItemViewModel
{
ObservableCollection<Item> selectedData = new ObservableCollection<Item>();
private ObservableCollection<Item> todaysItems;
public ObservableCollection<Item> TodaysItems
{
get { return todaysItems; }
private set
{
if (todaysItems != value)
{
todaysItems = value;
PropertyChanged(this, new PropertyChangedEventArgs("todaysItems"));
}
}
}
public ItemViewModel(IItemView itemView)
{
this.View = itemView;
this.View.Model = this;
List<Item> items = service.GetAllTestItems();
TodaysItems = new ObservableCollection<Item>(items);
selectedData.CollectionChanged += (sender, e) => UpdateSummary();
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private void NotifyPropertyChanged(string propertyName)
{
var handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
// How to get Selected Items from ListBox
public ObservableCollection<Item> SelectedData
{
get { return selectedData; }
set
{
selectedData = value;
}
}
private void UpdateSummary()
{
// here I can get selected data , I can find which Item is selected and then update its SubItems IsSelected (CLR) Property
// but something is not right here
}
}
XAML
<UserControl x:Class="ItemView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="clr-namespace:Microsoft.Practices.Composite.Presentation.Commands;assembly=Microsoft.Practices.Composite.Presentation"
xmlns:ZCom="clr-namespace:MyProj.Infrastructure;assembly=Infrastructure">
<Grid >
<ListBox ItemsSource="{Binding TodaysItems}">
<ListBox.ItemTemplate>
<DataTemplate >
<Border BorderThickness="1,1,1,1" CornerRadius="2,2,2,2" BorderBrush="Black">
<Grid MinHeight="50" Width="150" Height="Auto" Margin="0,0,0,0">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition/>
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="0"/>
</Grid.ColumnDefinitions>
<TextBlock Margin="4,4,2,2" Grid.Row="0" Width="Auto" TextWrapping="Wrap" Text="{Binding Path=Name}" />
<Grid Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" >
<Grid.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsSelected, RelativeSource=
{RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}}
}" Value="false">
<Setter Property="Grid.Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Style>
<Grid.RowDefinitions>
<RowDefinition Height="35"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Margin="2,4,2,2" Grid.Row="0" Width="Auto" FontSize="10" FontStyle="Italic" TextWrapping="Wrap" Text="{Binding Path=Note}"/>
<ListBox Style="{DynamicResource MyStyle}" Grid.Row="1" ItemsSource="{Binding Path=Modifiers}" SelectionMode="Multiple"
ZCom:ListBoxHelper.SelectedItems="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.SelectedData}">
<ListBox.ItemTemplate>
<DataTemplate >
<TextBlock Margin="2,2,2,2" TextWrapping="Wrap" Text="{Binding Path=Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
I am using ListBoxHelper ( in Infrastructure) from
http://marlongrech.wordpress.com/2009/06/02/sync-multi-select-listbox-with-viewmodel/
I get the view with Item and SubItems.
1) what is better way to set IsSelected Property of SubItems from nested ListBox
I will add a command which will store selected Item to Database once double clicked. SubItems will be stored as child record based on its IsSelected value.
2) Is there a way to make SubItems property of c# class observable . I would not want to change by adding Observable to the object as it will be in another assembly and may be used by other applications.
Edit 1:
Found somewhat helpful question
WPF Databinding to composite class patterns
But again for this I will have to inherit from INotifyPropertyChanged.
Edit 2:
Let me see if I can explain better- ListBox1 is Single select Mode and parent & ListBox 2 is multiselect. ListBox1 is binded (item source) to property which returns observablecollection. ListBox2 is binded to a Property in Item Class (Item.SubItems) which returns IList. Item Class has IsSelected Property.I want to be able to select subitems which should set IsSelected Property for the subItems to true. Knowing that there is no INotifyPropertyChanged inheritance in Item Class how can I achieve this. I assume that unless subitems come under some observable collection any changes will not be notified back to source. Using the selectedData property I can update the subitems by finding parent Item but then to update the view I will have to firePropertChanged for "items" which involves all items and subitems. I want only subitems change to be notified back by binding mechanism. Sorry if I am still not clear.
Edit 3:
I Guess there is no way but to implement INotifyPropertyChanged on Item class. Other way would be to implemnt a viewmodel which is very specific to needs of view but this will add up lot of code.
It's a little confusing what your overall goal here is.
If you're merely trying to get the selected items from a nested ListBox, Have you tried giving your ListBox an x:Name and exposing your SelectedItems via a property in your UserControl (ItemView) class?
public IList SelectedItems
{
get { return nestedListBox.SelectedItems; }
}
Can anyone help with the following - been playing about with this but can't for the life of me get it to work.
I've got a view model which contains the following properties;
public ObservableCollection<Rule> Rules { get; set; }
public Rule SelectedRule { get; set; }
In my XAML I've got;
<ListBox x:Name="lbRules" ItemsSource="{Binding Path=Rules}"
SelectedItem="{Binding Path=SelectedRule, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Name:" />
<TextBox x:Name="ruleName">
<TextBox.Text>
<Binding Path="Name" UpdateSourceTrigger="PropertyChanged" />
</TextBox.Text>
</TextBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
Now the ItemsSource works fine and I get a list of Rule objects with their names displayed in lbRules.
Trouble I am having is binding the SelectedRule property to lbRules' SelectedItem. I tried binding a textblock's text property to SelectedRule but it is always null.
<TextBlock Text="{Binding Path=SelectedRule.Name}" />
The error I'm seeing in the output window is:
BindingExpression path error: 'SelectedRule' property not found.
Can anyone help me with this binding - I can't see why it shouldn't find the SelectedRule property.
I then tried changing the textblock's text property as bellow, which works. Trouble is I want to use the SelectedRule in my ViewModel.
<TextBlock Text="{Binding ElementName=lbRules, Path=SelectedItem.Name}" />
Thanks very much for your help.
First off, you need to implement INotifyPropertyChanged interface in your view model and raise the PropertyChanged event in the setter of the Rule property. Otherwise no control that binds to the SelectedRule property will "know" when it has been changed.
Then, your XAML
<TextBlock Text="{Binding Path=SelectedRule.Name}" />
is perfectly valid if this TextBlock is outside the ListBox's ItemTemplate and has the same DataContext as the ListBox.
Inside the DataTemplate you're working in the context of a Rule, that's why you cannot bind to SelectedRule.Name -- there is no such property on a Rule.
To bind to the original data context (which is your ViewModel) you can write:
<TextBlock Text="{Binding ElementName=lbRules, Path=DataContext.SelectedRule.Name}" />
UPDATE: regarding the SelectedItem property binding, it looks perfectly valid, I tried the same on my machine and it works fine. Here is my full test app:
XAML:
<Window x:Class="TestWpfApplication.ListBoxSelectedItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ListBoxSelectedItem" Height="300" Width="300"
xmlns:app="clr-namespace:TestWpfApplication">
<Window.DataContext>
<app:ListBoxSelectedItemViewModel/>
</Window.DataContext>
<ListBox ItemsSource="{Binding Path=Rules}" SelectedItem="{Binding Path=SelectedRule, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Name:" />
<TextBox Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Window>
Code behind:
namespace TestWpfApplication
{
/// <summary>
/// Interaction logic for ListBoxSelectedItem.xaml
/// </summary>
public partial class ListBoxSelectedItem : Window
{
public ListBoxSelectedItem()
{
InitializeComponent();
}
}
public class Rule
{
public string Name { get; set; }
}
public class ListBoxSelectedItemViewModel
{
public ListBoxSelectedItemViewModel()
{
Rules = new ObservableCollection<Rule>()
{
new Rule() { Name = "Rule 1"},
new Rule() { Name = "Rule 2"},
new Rule() { Name = "Rule 3"},
};
}
public ObservableCollection<Rule> Rules { get; private set; }
private Rule selectedRule;
public Rule SelectedRule
{
get { return selectedRule; }
set
{
selectedRule = value;
}
}
}
}
Yocoder is right,
Inside the DataTemplate, your DataContext is set to the Rule its currently handling..
To access the parents DataContext, you can also consider using a RelativeSource in your binding:
<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ____Your Parent control here___ }}, Path=DataContext.SelectedRule.Name}" />
More info on RelativeSource can be found here:
http://msdn.microsoft.com/en-us/library/system.windows.data.relativesource.aspx
For me, I usually use DataContext together in order to bind two-depth property such as this question.
<TextBlock DataContext="{Binding SelectedRule}" Text="{Binding Name}" />
Or, I prefer to use ElementName because it achieves bindings only with view controls.
<TextBlock DataContext="{Binding ElementName=lbRules, Path=SelectedItem}" Text="{Binding Name}" />
There is a shorter version to bind to a selected item's property:
<TextBlock Text="{Binding Rules/Name}" />
since you set your itemsource to your collection, your textbox is tied to each individual item in that collection. the selected item property is useful in this scenario if you were trying to do a master-detail form, having 2 listboxes. you would bind the second listbox's itemsource to the child collection of rules. in otherwords the selected item alerts outside controls that your source has changed, internal controls(those inside your datatemplate already are aware of the change.
and to answer your question yes in most circumstances setting the itemsource is the same as setting the datacontext of the control.