Question

How do I set CommandParameter in the below code so that it will point to currently selected item?

<TreeView Grid.Column="0" HorizontalAlignment="Stretch" DockPanel.Dock="Left" ItemsSource="{Binding Path=ServerItems, UpdateSourceTrigger=PropertyChanged}">
<i:Interaction.Triggers>
    <i:EventTrigger EventName="MouseDoubleClick">
        <cmd:EventToCommand Command="{Binding ConnectServer}" PassEventArgsToCommand="True" CommandParameter="{Binding SelectedItem}" />
    </i:EventTrigger>
</i:Interaction.Triggers>
<TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding Databases}">
        <TextBlock Text="{Binding}" />
    </HierarchicalDataTemplate>
</TreeView.ItemTemplate>

ViewModel code:

public RelayCommand<ServerItem> ConnectServer {
    get;
    private set;
}

ConnectServer = new RelayCommand<ServerItem>(param => ConnectToServer(param));

public void ConnectToServer(ServerItem item) {
    MessageBox.Show(item.ToString());
}

Code execution doesn't get to ConnectToServer method because exception is thrown, telling me that cast from System.Windows.Input.MouseButtonEventArgs to type MadMin.Model.ServerItem is not possible.

Était-ce utile?

La solution

You'll need to use a RelativeSource Binding in order to reach the TreeView.SelectedItem property from within the Trigger. Try this Binding for your CommandParameter instead:

CommandParameter="{Binding SelectedItem, 
    RelativeSource={RelativeSource AncestorType={x:Type TreeView}}}"

Autres conseils

{Binding SelectedItem, RelativeSource={RelativeSource Self}}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top