让我先声明一下我对 C# 和 WPF 都很陌生。
我正在尝试连接一个集合Boolean
值到包含 6 个复选框的容器,并在按下按钮时存储这些值的状态。我假设有一种简单的方法可以做到这一点,因为将复选框绑定到集合似乎是一件非常自然的事情,但到目前为止我看到的所有解决方案似乎都过于复杂(例如:http://merill.net/2009/10/wpf-checked-listbox/).
我通过修改数据模板来创建复选框ListBox
并设置ItemsSource
of the ListBox
to the ObservableCollection
,但我的问题是我不知道要绑定什么IsChecked
到,因为我试图将它绑定到集合中的实际对象而不是对象的属性。
Use IsChecked="{Binding}"
直接绑定集合的项目。
<ListBox ItemsSource="{Binding MyBooleanCollection}" >
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Mode=OneWay}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
但是,无法使用此方法绑定到源。因为绑定在IsChecked
的财产CheckBox
不是绑定项的索引。因此,它不能更改集合,只能更改集合的项目。
Update
要解决该限制,您可以创建布尔值的包装器:
public class Wrapper<T> : INotifyPropertyChanged
{
private T value;
public T Value
{
get { return value; }
set
{
{
this.value = value;
OnPropertyChanged();
}
}
}
public static implicit operator Wrapper<T>(T value)
{
return new Wrapper<T> { value = value };
}
public static implicit operator T(Wrapper<T> wrapper)
{
return wrapper.value;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
这是一个用法示例:
public partial class MainWindow : Window
{
public ObservableCollection<Wrapper<bool>> MyBooleanCollection { get; private set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
MyBooleanCollection = new ObservableCollection<Wrapper<bool>>() { false, true, true, false, true };
}
}
在 XAML 中:
<CheckBox IsChecked="{Binding Value}"/>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)