ListView Binding with “IsSelected” Property of ListViewItem

前端 未结 2 1292
长发绾君心
长发绾君心 2021-02-04 19:15

I have following class

   public abstract class AbsTrinityEvent
   {
    public event IsSelected OnSelectedEvent; 

    bool _IsSelected;
    ITrinityEvent _objTr         


        
相关标签:
2条回答
  • 2021-02-04 19:44

    First off, you're much better off doing this in XAML. It makes things much clearer and shorter. I'm going to answer in both XAML and code-behind to demonstrate this.

    The easiest way is to make a Style applied to ListViewItem and using a Setter to apply the binding. On a ListViewItem, the DataContext is going to be your bound item (TrinityEventData in this case).

    Assuming you had your ListView in XAML:

    <ListView x:Name="lstview_Unack">
        <ListView.Resources>
            <Style TargetType="{x:Type ListViewItem}">
                <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
            </Style>
        </ListView.Resources>
    </ListView>
    

    In code, you have to construct the Style, Setter, and Binding by hand:

    Style listViewItemStyle = new Style { TargetType = typeof(ListViewItem) };
    listViewItemStyle.Setters.Add(new Setter
    {
        Property = ListViewItem.IsSelectedProperty,
        Value = new Binding { Path = new PropertyPath("IsSelected") }
    });
    lstview_Unack.Resources.Add(typeof(ListViewItem), listViewItemStyle);
    

    There are issues with this and virtualization, however. If your ListViewItems get virtualized, you might be unselecting items in the ListView but the binding won't be firing because your ListViewItem won't exist.

    0 讨论(0)
  • 2021-02-04 20:00

    What worked for me is:

    <ListView x:Name="lstview_Unack">
        <ListView.ItemContainerStyle>
            <Style TargetType="{x:Type ListViewItem}">
                <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
            </Style>
        </ListView.ItemContainerStyle>
    </ListView>
    
    0 讨论(0)
提交回复
热议问题