获取WPF中的列表视图复选框状态
本文关键字:视图 复选框 状态 列表 WPF 获取 | 更新日期: 2023-09-27 18:04:31
我有一个包含复选框的列表视图。我怎样才能得到它是否被检查过?
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>
或者当用户取消选中或选中集合中的复选框"值"时是否可能更改?
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只是在集合的内容发生变化时引发事件,而不是在UserData类的属性发生变化时引发事件。你可以考虑让UserData实现INotifyPropertyChanged。这样你就可以编程地设置Value属性,并且UI绑定复选框将被自动选中/不选中。
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;
}
你应该让UserData实现INotifyPropertyChanged,然后使Value属性在更新时通知。如果不采取这两个步骤,绑定将无法正常工作。完成这两件事之后,UserData的实例将包含复选框的值。
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");
};
}
}