如何在下面的代碼中設置CommandParameter
,以便它指向當前選定的項目?TreeViewItem MouseDoubleClick事件和MvvmLight
<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>
視圖模型代碼:
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
是不可能的。
大約只是'CommandParameter = 「{結合的SelectedItem}」'怎麼辦?那是什麼回報? – Sheridan
請查看我編輯的問題。 –
好的,那麼'CommandParameter =「{Binding SelectedItem,RelativeSource = {RelativeSource AncestorType = {x:Type TreeView}}}''? – Sheridan