listboxitem中的复选框随机选中/取消选中

时间:2010-11-26 16:29:57

标签: checkbox listbox silverlight-4.0

我有一个ListBox。在每个ListBoxItem中有两个TextBlock和一个CheckBox。首先,我检查了所有复选框。取消选中一个复选框然后滚动后,复选框将被随机选中并取消选中。

怎么了?

代码:

  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); 
          }
      }                                 
  }
  // 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>

2 个答案:

答案 0 :(得分:1)

解决方案:

    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"); }}             
        }            
    }

答案 1 :(得分:1)

将绑定模式设为TwoWay

<CheckBox IsChecked="{Binding show, Mode=TwoWay}" />