TreeViewItem MouseDoubleClick事件和MvvmLight

时间:2014-02-24 20:39:22

标签: wpf mvvm-light

如何在下面的代码中设置CommandParameter,使其指向当前所选的项目?

<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代码:

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

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

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

代码执行无法进入ConnectToServer方法,因为抛出了异常,告诉我从System.Windows.Input.MouseButtonEventArgs转换为类型MadMin.Model.ServerItem是不可能的。

2 个答案:

答案 0 :(得分:2)

您需要使用RelativeSource Binding才能从TreeView.SelectedItem内到达Trigger媒体资源。请改为Binding代替CommandParameter

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

答案 1 :(得分:0)

{Binding SelectedItem, RelativeSource={RelativeSource Self}}