ListViewItem IsSelected Binding - Works for WPF, but not for WinRT

徘徊边缘 提交于 2019-11-30 04:14:14

WinRT doesn't support bindings in setters at all as of Windows 8.0. Bing for workarounds.

A good and easy way to do this is to subclass ListView

public class MyListView : ListView
    {
        protected override void PrepareContainerForItemOverride(Windows.UI.Xaml.DependencyObject element, object item)
        {
            base.PrepareContainerForItemOverride(element, item);
            // ...
            ListViewItem listItem = element as ListViewItem;
            Binding binding = new Binding();
            binding.Mode = BindingMode.TwoWay;
            binding.Source = item;
            binding.Path = new PropertyPath("Selected");
            listItem.SetBinding(ListViewItem.IsSelectedProperty, binding);
        }
    }

Alternatively, it seems you can also do it with WinRT XAML Toolkit.

<ListView
            x:Name="lv"
            Grid.Row="1"
            Grid.Column="1"
            SelectionMode="Multiple"
            HorizontalAlignment="Left"
            Width="500">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextBlock
                        Extensions:ListViewItemExtensions.IsSelected="{Binding IsSelected}"
                        Extensions:ListViewItemExtensions.IsEnabled="{Binding IsEnabled}"
                        Text="{Binding Text}"
                        Margin="15,5"
                        FontSize="36" />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

Personally, I used the first approach because it's more flexible and I needed to bind a few Automation Properties.

Credits to ForInfo and ehuna: http://social.msdn.microsoft.com/Forums/windowsapps/en-US/9a0adf35-fdad-4419-9a34-a9dac052a2e3/listviewitemisselected-data-binding-in-style-setter-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!