开发者

Get listview checkbox status in WPF

I have a list view which contains checkboxes. Ho开发者_Python百科w I can get if it is checked or not?

XAML:

 <ListView Name="listview1" ItemsSource="{Binding UserCollection}">
     <ListView.View>
         <GridView>
             <GridViewColumn  Header="Discription" Width="170">
                 <GridViewColumn.CellTemplate>
                     <DataTemplate>
                         <TextBlock Text="{Binding Path=Discription}" Width="Auto"/>
                     </DataTemplate>
                 </GridViewColumn.CellTemplate>
             </GridViewColumn>
             <GridViewColumn  Header="Value" >
                 <GridViewColumn.CellTemplate>
                     <DataTemplate>
                         <StackPanel>
                             <CheckBox IsChecked="{Binding Path=Value}" Content="{Binding Path=Value}" Width="70" Name="ckBox1"/>
                         </StackPanel>
                     </DataTemplate>
                 </GridViewColumn.CellTemplate>
             </GridViewColumn>
         </GridView>
     </ListView.View>
 </ListView>

OR does it possible when user unchecks or checks checkboxes 'Value' in collection changed?

ObservableCollection<UserData> _UserCollection = new ObservableCollection<UserData>();
public ObservableCollection<UserData> UserCollection
{
    get { return _UserCollection; }
}

public class UserData
{
    public string Discription { get; set; }
    public bool Value { get; set; }
}


ObservableCollection simply raises events when the contents of the collection change, not when a property of one of your UserData classes change. You may want to consider making UserData implement INotifyPropertyChanged. This way you can programaticaly set the Value property and the UI bound checkbox will automatically be checked/unchecked appropriately.

    public class UserData : INotifyPropertyChanged
    {
       private bool m_value;

       public bool Value
       {
          get { return m_value; }
          set
          {
             if (m_value == value)
                return;
             m_value = value;
             if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Value"));
          }
       }

       public event PropertyChangedEventHandler PropertyChanged;
   }


You should have UserData implement INotifyPropertyChanged and then make the Value property notify when it is updated. Your bindings won't work properly if you don't take these two steps. Once you have done these two things, then the instance of UserData will contain the value of the checkbox.

public class UserData : INotifyPropertyChanged
{
    /* Sample code : missing the implentation for INotifyProperty changed */

    private bool Value = true;

    public bool Value
    {
        get{ return _value;}
        set{ _value= value;
             RaiseNotification("Value");
        };
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜