使用ListBoxItemExtensions.从WinRt Xaml工具包中选择不支持双向绑定

本文关键字:不支持 选择 绑定 工具包 ListBoxItemExtensions WinRt Xaml 使用 | 更新日期: 2023-09-27 18:18:56

在Windows RT应用程序(c#)与WinRt Xaml工具包,我使用这个:

<ListBox ItemsSource="{Binding Path=FilterBaseFields}" SelectionMode="Multiple">
            <ListBox.ItemTemplate >
                <DataTemplate  >
                    <TextBox Text="{Binding Path=Key, Mode=TwoWay}" 
                  extensions:ListBoxItemExtensions.IsSelected="{Binding Path=IsSelected, Mode=TwoWay}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

对于文本双向绑定工作得很好,但对于扩展:ListBoxItemExtensions。IsSelected -不工作(只从源到视图工作)。
有什么想法吗?

使用ListBoxItemExtensions.从WinRt Xaml工具包中选择不支持双向绑定

我问它已经在WinRT XAML工具包讨论中,该工具包的作者philip Skakun回答:

这是正确的。这似乎是这个性质的一个限制。我们需要创建一个不同的接口来支持双向绑定。类似于使用我在这里描述的模式的"isselectebinding"属性:http://blog.onedevjob.com/2011/10/26/workaround-for-binding-not-supported-on-stylesettervalue-in-silverlight/也许当我有机会的时候,我会把它添加到工具包中。

我用克莱门斯的答案解决了我的问题。

它看起来像:

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