在WinRT应用程序(C#)中,我有List<Item> items
,绑定到ListBox
。
Class Item
有两个字段:string Name
和bool IsSelected
。如您所知,我想将IsSelected
字段绑定到ListBoxItem的IsSelected属性。
为什么我需要这个?为什么我没有使用SelectedItems
的{{1}}属性?
ListBox
时,我已经有了一些项目,必须是ListBox
我在找什么? 我正在寻找优雅的解决方案,就像在WPF中一样:
IsSelected = true
但我们都知道,WinRT根本不支持setter中的绑定。
我还检查了nice post博客中的Filip Skakun - 这是解决方案之一,但我需要自己写一些 <ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</Style>
</ListBox.ItemContainerStyle>
。
现在,我知道解决问题的两种方法:
BindingBuilder/BindingHelper
的{{1}}属性并存储其他项目集合。 - 我不喜欢这样在理想情况下,我想为此使用本机解决方案,或者可能已经为我的情况编写/测试过嵌套SelectedItems
的人 - 它也会有所帮助。
答案 0 :(得分:2)
如何创建派生的ListBox:
public class MyListBox : ListBox
{
protected override void PrepareContainerForItemOverride(
DependencyObject element, object item)
{
base.PrepareContainerForItemOverride(element, item);
if (item is Item)
{
var binding = new Binding
{
Source = item,
Path = new PropertyPath("IsSelected"),
Mode = BindingMode.TwoWay
};
((ListBoxItem)element).SetBinding(ListBoxItem.IsSelectedProperty, binding);
}
}
}