ListView Binding with “IsSelected” Property of ListViewItem

前端 未结 2 1291
长发绾君心
长发绾君心 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:

    
        
            
        
    
    

    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.

提交回复
热议问题