سؤال

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.

هل كانت مفيدة؟

المحلول

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}}}"

نصائح أخرى

{Binding SelectedItem, RelativeSource={RelativeSource Self}}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top