WPF: how to bind m object property from MouseLeftButtonUp event in my listview item click

182 Views Asked by At

So I have this object:

public class Test : INotifyPropertyChanged
    {
        public string Name { get; set; }

        private bool isSelected;
        public bool IsSelected
        {
            get { return isSelected; }
            set
            {
                isSelected = value;
                NotifyPropertyChanged("IsSelected");
            }
        }

        public Test(string name, string path, bool selected)
        {
            Name = name;
            Path = path;
            isSelected = selected;
        }

        public override string ToString()
        {
            return Name;
        }

        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

So I have ListView bind with my object (Test) and when the user click on ListViewItem I want to change my IsSelected property from true to false (or Or vice versa...)

And MouseLeftButtonUp:

<ListView Name="listViewTests" ItemsSource="{Binding Tests}">
      <i:EventTrigger EventName="MouseLeftButtonUp">
            <i:InvokeCommandAction Command="{Binding MouseLeftButtonUpCommand}"
                                   CommandParameter="{Binding ElementName=listViewTests, Path=SelectedItem}"/>
            </i:EventTrigger>
     </i:Interaction.Triggers>
</ListView>

My Execute Command:

    public void Execute(object parameter)
    {
        Test test = parameter as Test;
        if (test != null)
            {

            }
    }

So instead of change my object property inside this Execute method i wonder how to do that in XAML

1

There are 1 best solutions below

0
On

You can setup the ItemContainerStyle and bind the ListBoxItem.IsSelected property to your data model Test.IsSelected:

<ListView ItemsSource="{Binding Tests}">
  <ListView.ItemContainerStyle>

    <!-- The DataContext of this Style is the ListBoxItem.Content (a 'Test' instance) -->
    <Style TargetType="ListBoxItem">
      <Setter Property="IsSelected" Value="{Binding IsSelected}" />
    </Style>
  </ListView.ItemContainerStyle>
</ListView>