绑定到树视图选定的项目
本文关键字:项目 视图 绑定 | 更新日期: 2023-09-27 18:16:07
我试图将TreeView项目双击事件绑定到我的视图模型。它实际上是工作的,只有我想知道哪个项目被选中,并绑定到SelectedItem不起作用(参数为null):
<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());
}
}
另一个问题-如果我让这个工作-我将得到什么在参数参数-我的意思是-我能以某种方式得到我的可观察集合的底层项目?
您的参数绑定不正确CommandBehaviors:MouseDoubleClick.CommandParameter="{Binding Path=SelectedItem}"
。这里你试图绑定到SelectedItem
属性的视图模型,但这个属性属于TreeView
。我想你可以在Visual Studio输出窗口中看到相应的绑定错误。
试试下面的代码:
CommandBehaviors:MouseDoubleClick.CommandParameter="{Binding Path=SelectedItem, RelativeSource={RelativeSource Self}}"
您可以在这里找到有关RelativeSource
的更多信息:WPF中的RelativeSources
关于您的第二个问题-是的,您将从您的集合中收到您的底层项目作为命令参数。