我正在尝试将 TreeView 项目双击事件绑定到我的视图模型。它实际上有效,只是我想知道选择了哪个项目,并且绑定到 SelectedItem 不起作用(参数为空):
<TreeView CommandBehaviors:MouseDoubleClick.Command="{Binding Connect}" CommandBehaviors:MouseDoubleClick.CommandParameter="{Binding Path=SelectedItem}"
Grid.Column="0" HorizontalAlignment="Stretch" DockPanel.Dock="Left" ItemsSource="{Binding Path=ServerItems, UpdateSourceTrigger=PropertyChanged}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Databases}">
<TextBlock Text="{Binding}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
命令行为:
public class MouseDoubleClick {
public static DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached("Command",
typeof(ICommand),
typeof(MouseDoubleClick),
new UIPropertyMetadata(CommandChanged));
public static DependencyProperty CommandParameterProperty =
DependencyProperty.RegisterAttached("CommandParameter",
typeof(object),
typeof(MouseDoubleClick),
new UIPropertyMetadata(null));
public static void SetCommand(DependencyObject target, ICommand value) {
target.SetValue(CommandProperty, value);
}
public static void SetCommandParameter(DependencyObject target, object value) {
target.SetValue(CommandParameterProperty, value);
}
public static object GetCommandParameter(DependencyObject target) {
return target.GetValue(CommandParameterProperty);
}
private static void CommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e) {
Control control = target as Control;
if (control != null) {
if ((e.NewValue != null) && (e.OldValue == null)) {
control.MouseDoubleClick += OnMouseDoubleClick;
} else if ((e.NewValue == null) && (e.OldValue != null)) {
control.MouseDoubleClick -= OnMouseDoubleClick;
}
}
}
private static void OnMouseDoubleClick(object sender, RoutedEventArgs e) {
Control control = sender as Control;
ICommand command = (ICommand)control.GetValue(CommandProperty);
object commandParameter = control.GetValue(CommandParameterProperty);
command.Execute(commandParameter);
}
}
ViewModel 的相关部分:
public class MainViewModel : BaseViewModel {
#region commands
private ICommand _connect;
public ICommand Connect {
get {
if (_connect == null) {
_connect = new PGAdmin.Commands.Generic.RelayCommand(param => ConnectToDatabase(param));
}
return _connect;
}
set {
_connect = value;
}
}
#endregion
public void ConnectToDatabase(object param) {
DebugPopup.Show(param.ToString());
}
}
另一个问题 - 如果我完成这项工作 - 我会在 param 参数中得到什么 - 我的意思是 - 我可以以某种方式访问我的 observable 集合的底层项目吗?