Checkboxes in listboxitem checked/unchecked randomly
I have a ListBox. In every ListBoxItem there are two TextBlocks and one CheckBox. At first I have all checkboxes checked. After unchecking one checkbox and then scrolling, the checkboxes get checked and unchecked randomly.
What's wrong?
Code:
cut from [X.xaml.cs]
//
lbx.ItemsSource = settings.itemSettings; // settings is instance of Settings
// holds data for the listbox
public class Settings
{
public ObservableCollection<ItemSetting> itemSettings; // <-lbx.ItemSource
public Settings(ObservableCollection<string> texts)
{
itemSettings = new ObservableCollection<ItemSetting>();
for (int i = 0; i < texts.Count; i++)
{
ItemSetting s = new ItemSetting();
s.number = (i + 1).ToString(); // the position number
s.text = texts[i]; // the message
s.show = true; // true=show or false=hide
itemSettings.Add(s);
}
} 开发者_StackOverflow社区
}
// holds data for listbox item
public class ItemSetting
{
public string number { get; set; }
public string text { get; set; }
public bool show { get; set; }
}
------------------------------------------------------------------------------
cut from [X.xaml] --- the listbox
<ListBox Name="lbx">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding number}" />
<TextBlock Text="{Binding text}" />
<CheckBox IsChecked="{Binding show}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Solution:
Binding mode TwoWay
<CheckBox IsChecked="{Binding show, Mode=TwoWay}" />
Implement INotifyPropertyChanged
public class ItemSetting : System.ComponentModel.INotifyPropertyChanged
{
public string questionNumber { get; set; }
public string questionText { get; set; }
//public bool show { get; set; }
private bool bShow;
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
void Notify(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propName));
}
}
public bool show
{
get {return this.bShow;}
set {if (value != this.bShow) { this.bShow = value; Notify("show"); }}
}
}
Make the binding mode as TwoWay
<CheckBox IsChecked="{Binding show, Mode=TwoWay}" />
精彩评论