An MVVM button event with a list view not getting the selected item
-
14-06-2021 - |
سؤال
I am trying to get the selectedItem from my list view. I am using MVVM light toolkit and the EventToCommand on a button.
My listView is bound to an ObservableCollection which is correctly binding. Here is the listView xaml:
<ListView Name="serverListView"
Grid.Row="3"
Grid.Column="0"
Grid.ColumnSpan="2"
ItemsSource="{Binding Servers}"
ItemTemplate="{StaticResource ServerList}"
SelectionMode="Single"
BorderThickness="0"/>
I then have a button which I am using Interaction.Triggers with a mvvm EventToCommand, I am not sure if the selectedItem binding is correct. The event is firing correctly through a Relay Command (mvvm light toolkit) but I am getting null every time.
Here is my button xaml;
<Button x:Name="LoadButton"
Content="Load Server"
Grid.Column="0"
Grid.Row="4"
Grid.ColumnSpan="2">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<mvvm:EventToCommand Command="{Binding ButtonClick, Mode=OneWay}"
CommandParameter="{Binding SelectedItem, ElementName=serverListView}"
MustToggleIsEnabledValue="True"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
Relay Command:
this.ButtonClick = new RelayCommand<object>(new Action<object>(this.GetClickEvent));
المحلول
You should as well bind the SelectedItem property of the listview to a property (SelectedServer) of your viewmodel, and change your EventToCommand
CommandParameter="{Binding SelectedItem, ElementName=serverListView}"
to
CommandParameter="{Binding SelectedServer}"
نصائح أخرى
get rid of the commandparameter binding, create a SelectedServer property in your viewmodel and the Command in your viewmodel without parameter
<ListView Name="serverListView"
Grid.Row="3"
Grid.Column="0"
Grid.ColumnSpan="2"
ItemsSource="{Binding Servers}"
ItemTemplate="{StaticResource ServerList}"
SelectedItem="{Binding SelectedServer}"
SelectionMode="Single"
BorderThickness="0"/>
<Button Command="{Binding MyCommand}" />
in your viewmodel you have all information you need to do your command logic.