Reputation: 775
I am tying to bind a list of custom objects as a source to listbox where my listbox has user template as
<DataTemplate x:Key="UserTemplate1" >
<StackPanel Orientation="Horizontal">
<TextBlock Name="vmname" Text="{Binding }" Width="100"/>
<CheckBox Name="cb" IsChecked="{Binding ischeck}"/>
</StackPanel>
</DataTemplate>
and I used this template as datatype for listbox
<ListBox Name="listbox3" Visibility="Hidden" Height="134" Width="156" Margin="515,82,62,104" IsSynchronizedWithCurrentItem="True" ItemTemplate="{StaticResource UserTemplate1}" />
I have list of objects of custom datatype
class item{
string name;
bool val;
}
I am not able to bind this list to listbox. i want to bind list in such a way that whenever change is made to checkbox in list, they should reflect in list of objects(item).
listbox3.itemsource = list_items
This does not work for me
Here, I am not able to bind listbox3 to the list of objects of class checkvm.
Upvotes: 1
Views: 1260
Reputation: 132588
You are binding your CheckBox.Checked
to "ischeck", however your item
class does not contain a property called ischeck
.
For binding to a list of items like this :
class item{
string name;
bool val;
}
Your DataTemplate's bindings need to look like this :
<DataTemplate x:Key="UserTemplate1" >
<StackPanel Orientation="Horizontal">
<TextBlock Name="vmname" Text="{Binding name}" Width="100"/>
<CheckBox Name="cb" IsChecked="{Binding val}"/>
</StackPanel>
</DataTemplate>
Also note that your class should implement INotifyPropertyChanged
if you want to be able to change your item in code behind and have it automatically update the UI, or if you want to do any kind of change notification.
As a side note, I hate your (lack of) naming convention. I would highly recommend googling a standard .Net naming convention and using it. :)
Upvotes: 1
Reputation: 5566
You problem is that the changes (which are reflected in the instance of the item class) are not automatically reflected to another view / binding to an item of the list. If you want to notify the second view that a property of the item
instance has changed it has to implement INotifyPropertyChanged
.
The easiest way is achieve that is to use a MVVM-framework. Your item class should extend the ViewModel class which implements the change notification.
example:
public class Item : ViewModelBase
{
private string _Name;
public string Name
{
get
{
return _Name;
}
set
{
if (_Name != value)
{
_Name = value;
RaisePropertyChanged(() => this.Name);
}
}
}
private bool _IsSelected;
public bool IsSelected
{
get
{
return _IsSelected;
}
set
{
if (_IsSelected != value)
{
_IsSelected = value;
RaisePropertyChanged(() => this.IsSelected);
}
}
}
}
Upvotes: 1