Search code examples
c#xamlwindows-runtimewinrt-xamlwinrt-xaml-toolkit

Using ListBoxItemExtensions.IsSelected from WinRt Xaml Toolkit doesn't work TwoWay Binding


In Windows RT App (c#) with WinRt Xaml Toolkit i use this:

<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>

For Text TwoWay Binding works great, but for extensions:ListBoxItemExtensions.IsSelected - doesn't work (work only from source to view).
Have any Idea?


Solution

  • I asked it's already on WinRT XAML Toolkit discussion and author of that toolkit Filip Skakun answered:

    That's right. It seems to be a limitation of this property. We would need to create a different one to support two way binding. Something like an "IsSelectedBinding" property using the pattern I described here: http://blog.onedevjob.com/2011/10/26/workaround-for-binding-not-supported-on-stylesettervalue-in-silverlight/ Maybe when I get a chance I will add that to the toolkit.

    And I solve my problem with using Clemens answer.

    It looks like:

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