如何在下面的代码中设置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
是不可能的。
答案 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}}