我最近在我的代码中实现了一个解决方案,允许我在我的视图模型中绑定到我的命令。以下是我使用的方法的链接:https://code.msdn.microsoft.com/Event-to-Command-24d903c8。我在链接中使用了第二种方法。您可以假设我的代码与此代码非常相似。这很好用。但是,我还需要为此双击绑定命令参数。我该如何设置?
以下是我项目的背景知识。这个项目背后的一些设置可能看起来很奇怪,但必须以这种方式完成,因为我赢得了很多细节。首先要注意的是,这种绑定设置发生在多值转换器内部。这是我生成新元素的代码:
DataTemplate dt = new DataTemplate();
dt.DataType = typeof(Button);
FrameworkElementFactory btn = new FrameworkElementFactory(typeof(Button));
btn.SetValue(Attached.DoubleClickCommandProperty, ((CardManagementViewModel)values[1]).ChangeImageCommand);
dt.VisualTree = btn;
values [1]是DataContext,这里是viewmodel。视图模型包含以下内容:
private RelayCommand _ChangeImageCommand;
public ICommand ChangeImageCommand
{
get
{
if (_ChangeImageCommand == null)
{
_ChangeImageCommand = new RelayCommand(
param => this.ChangeImage(param)
);
}
return _ChangeImageCommand;
}
}
private void ChangeImage(object cardParam)
{
}
如何传递该命令参数?我以前曾多次使用XAML捆绑所有这些东西,但从来没有用C#做过。感谢您的帮助!
修改
以下是我的问题的完整示例。虽然我知道这个样本没有实际用途,但是为了解决这个问题,我们只能运行它。
让我们说我想要显示一个ObservableCollection字符串。这些包含在viewmodel中。
private ObservableCollection<string> _MyList;
public ObservableCollection<string> MyList { get { return _MyList; } set { if (_MyList != value) { _MyList = value; RaisePropertyChanged("MyList"); } } }
public ViewModel()
{
MyList = new ObservableCollection<string>();
MyList.Add("str1");
MyList.Add("str2");
MyList.Add("str3");
}
所以负责我团队用户界面的人就把这个给了我
<ContentControl>
<ContentControl.Content>
<MultiBinding Converter="{StaticResource ResourceKey=MyConverter}">
<Binding Path="MyList"/>
<Binding />
</MultiBinding>
</ContentControl.Content>
</ContentControl>
现在让我们说UI用户和我的项目经理决定密谋反对我让我的生活变成一个生活地狱,所以他们告诉我,我需要创建一个列表框来显示这些项目作为按钮,而不是在XAML中,但在ContentControl内容绑定的转换器中。所以我这样做:
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
ListBox lb = new ListBox();
lb.ItemsSource = (ObservableCollection<string>)values[0];
DataTemplate dt = new DataTemplate();
dt.DataType = typeof(Button);
FrameworkElementFactory btn = new FrameworkElementFactory(typeof(Button));
btn.SetValue(Button.WidthProperty, 100D);
btn.SetValue(Button.HeightProperty, 50D);
btn.SetBinding(Button.ContentProperty, new Binding());
dt.VisualTree = btn;
lb.ItemTemplate = dt;
return lb;
}
此成功显示列表框,所有项目均为按钮。第二天,我的白痴项目经理在视图模型中创建了一个新命令。其目的是如果双击其中一个按钮,则在列表框中添加所选项目。不单击,但双击!这意味着我无法使用CommandProperty,或者更重要的是,CommandParameterProperty。他在viewmodel中的命令看起来像这样:
private RelayCommand _MyCommand;
public ICommand MyCommand
{
get
{
if (_MyCommand == null)
{
_MyCommand = new RelayCommand(
param => this.MyMethod(param)
);
}
return _MyCommand;
}
}
private void MyMethod(object myParam)
{
MyList.Add(myParam.ToString());
}
因此,经过一些谷歌搜索后,我找到一个将我的DoubleClick事件转换为附加属性的类。这是班级:
public class Attached
{
static ICommand command;
public static ICommand GetDoubleClickCommand(DependencyObject obj)
{
return (ICommand)obj.GetValue(DoubleClickCommandProperty);
}
public static void SetDoubleClickCommand(DependencyObject obj, ICommand value)
{
obj.SetValue(DoubleClickCommandProperty, value);
}
// Using a DependencyProperty as the backing store for DoubleClickCommand. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DoubleClickCommandProperty =
DependencyProperty.RegisterAttached("DoubleClickCommand", typeof(ICommand), typeof(Attached), new UIPropertyMetadata(null, CommandChanged));
static void CommandChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var fe = obj as FrameworkElement;
command = e.NewValue as ICommand;
fe.AddHandler(Button.MouseDoubleClickEvent, new RoutedEventHandler(ExecuteCommand));
}
static void ExecuteCommand(object sender, RoutedEventArgs e)
{
var ele = sender as Button;
command.Execute(null);
}
}
然后回到转换器中,我将此行放在 dt.VisualTree = btn; 之上:
btn.SetValue(Attached.DoubleClickCommandProperty, ((ViewModel)values[1]).MyCommand);
这成功点击了我的项目经理的命令,但我仍然需要传递列表框的所选项目。然后我的项目经理告诉我,我不能再触摸视图模型了。这是我被困的地方。如何仍然将列表框的选定项目发送到视图模型中的项目经理的命令?
以下是此示例的完整代码文件:
ViewModel.cs
using System.Collections.ObjectModel;
using System.Windows.Input;
using WpfApplication2.Helpers;
namespace WpfApplication2
{
public class ViewModel : ObservableObject
{
private ObservableCollection<string> _MyList;
private RelayCommand _MyCommand;
public ObservableCollection<string> MyList { get { return _MyList; } set { if (_MyList != value) { _MyList = value; RaisePropertyChanged("MyList"); } } }
public ViewModel()
{
MyList = new ObservableCollection<string>();
MyList.Add("str1");
MyList.Add("str2");
MyList.Add("str3");
}
public ICommand MyCommand
{
get
{
if (_MyCommand == null)
{
_MyCommand = new RelayCommand(
param => this.MyMethod(param)
);
}
return _MyCommand;
}
}
private void MyMethod(object myParam)
{
MyList.Add(myParam.ToString());
}
}
}
MainWindow.xaml
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:helpers="clr-namespace:WpfApplication2.Helpers"
xmlns:Converters="clr-namespace:WpfApplication2.Helpers.Converters"
xmlns:local="clr-namespace:WpfApplication2"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<Window.Resources>
<Converters:MyConverter x:Key="MyConverter"/>
</Window.Resources>
<ContentControl>
<ContentControl.Content>
<MultiBinding Converter="{StaticResource ResourceKey=MyConverter}">
<Binding Path="MyList"/>
<Binding />
</MultiBinding>
</ContentControl.Content>
</ContentControl>
</Window>
MyConverter.cs
using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace WpfApplication2.Helpers.Converters
{
public class MyConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
ListBox lb = new ListBox();
lb.ItemsSource = (ObservableCollection<string>)values[0];
DataTemplate dt = new DataTemplate();
dt.DataType = typeof(Button);
FrameworkElementFactory btn = new FrameworkElementFactory(typeof(Button));
btn.SetValue(Button.WidthProperty, 100D);
btn.SetValue(Button.HeightProperty, 50D);
btn.SetBinding(Button.ContentProperty, new Binding());
btn.SetValue(Attached.DoubleClickCommandProperty, ((ViewModel)values[1]).MyCommand);
// Somehow create binding so that I can pass the selected item of the listbox to the
// above command when the button is double clicked.
dt.VisualTree = btn;
lb.ItemTemplate = dt;
return lb;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
Attached.cs
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace WpfApplication2.Helpers
{
public class Attached
{
static ICommand command;
public static ICommand GetDoubleClickCommand(DependencyObject obj)
{
return (ICommand)obj.GetValue(DoubleClickCommandProperty);
}
public static void SetDoubleClickCommand(DependencyObject obj, ICommand value)
{
obj.SetValue(DoubleClickCommandProperty, value);
}
// Using a DependencyProperty as the backing store for DoubleClickCommand. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DoubleClickCommandProperty =
DependencyProperty.RegisterAttached("DoubleClickCommand", typeof(ICommand), typeof(Attached), new UIPropertyMetadata(null, CommandChanged));
static void CommandChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var fe = obj as FrameworkElement;
command = e.NewValue as ICommand;
fe.AddHandler(Button.MouseDoubleClickEvent, new RoutedEventHandler(ExecuteCommand));
}
static void ExecuteCommand(object sender, RoutedEventArgs e)
{
var ele = sender as Button;
command.Execute(null);
}
}
}
ObservableObject.cs
using System;
using System.ComponentModel;
using System.Diagnostics;
namespace WpfApplication2.Helpers
{
public class ObservableObject : INotifyPropertyChanged
{
#region Debugging Aides
/// <summary>
/// Warns the developer if this object does not have
/// a public property with the specified name. This
/// method does not exist in a Release build.
/// </summary>
[Conditional("DEBUG")]
[DebuggerStepThrough]
public virtual void VerifyPropertyName(string propertyName)
{
// Verify that the property name matches a real,
// public, instance property on this object.
if (TypeDescriptor.GetProperties(this)[propertyName] == null)
{
string msg = "Invalid property name: " + propertyName;
if (this.ThrowOnInvalidPropertyName)
throw new Exception(msg);
else
Debug.Fail(msg);
}
}
/// <summary>
/// Returns whether an exception is thrown, or if a Debug.Fail() is used
/// when an invalid property name is passed to the VerifyPropertyName method.
/// The default value is false, but subclasses used by unit tests might
/// override this property's getter to return true.
/// </summary>
protected virtual bool ThrowOnInvalidPropertyName { get; private set; }
#endregion // Debugging Aides
#region INotifyPropertyChanged Members
/// <summary>
/// Raises the PropertyChange event for the property specified
/// </summary>
/// <param name="propertyName">Property name to update. Is case-sensitive.</param>
public virtual void RaisePropertyChanged(string propertyName)
{
this.VerifyPropertyName(propertyName);
OnPropertyChanged(propertyName);
}
/// <summary>
/// Raised when a property on this object has a new value.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises this object's PropertyChanged event.
/// </summary>
/// <param name="propertyName">The property that has a new value.</param>
protected virtual void OnPropertyChanged(string propertyName)
{
this.VerifyPropertyName(propertyName);
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
#endregion // INotifyPropertyChanged Members
}
}
RelayCommand.cs
using System;
using System.Diagnostics;
using System.Windows.Input;
namespace WpfApplication2.Helpers
{
public class RelayCommand : ICommand
{
#region Fields
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
#endregion // Fields
#region Constructors
/// <summary>
/// Creates a new command that can always execute.
/// </summary>
/// <param name="execute">The execution logic.</param>
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
/// <summary>
/// Creates a new command.
/// </summary>
/// <param name="execute">The execution logic.</param>
/// <param name="canExecute">The execution status logic.</param>
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
#endregion // Constructors
#region ICommand Members
[DebuggerStepThrough]
public bool CanExecute(object parameters)
{
return _canExecute == null ? true : _canExecute(parameters);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameters)
{
_execute(parameters);
}
#endregion // ICommand Members
}
}
再次,谢谢你的帮助!!!
答案 0 :(得分:2)
您发布的代码实际上并非最小或完整示例。至少,它缺少CardManagementViewModel
类型,当然示例似乎是基于原始代码,并没有尝试将其缩减为 minimal 示例
因此,我没有花太多时间查看所有代码,没关系,我是否懒得编译并运行它。但是,原始编辑中缺少的主要内容是附加属性的实现。所以有了这个,我建议你改变你的Attached
课程,看起来像这样:
public class Attached
{
public static ICommand GetDoubleClickCommand(DependencyObject obj)
{
return (ICommand)obj.GetValue(DoubleClickCommandProperty);
}
public static void SetDoubleClickCommand(DependencyObject obj, ICommand value)
{
obj.SetValue(DoubleClickCommandProperty, value);
}
public static object GetDoubleClickCommandParameter(DependencyObject obj)
{
return obj.GetValue(DoubleClickCommandParameterProperty);
}
public static void SetDoubleClickCommandParameter(DependencyObject obj, object value)
{
obj.SetValue(DoubleClickCommandParameterProperty, value);
}
// Using a DependencyProperty as the backing store for DoubleClickCommand. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DoubleClickCommandProperty =
DependencyProperty.RegisterAttached("DoubleClickCommand", typeof(ICommand), typeof(Attached), new UIPropertyMetadata(null, CommandChanged));
public static readonly DependencyProperty DoubleClickCommandParameterProperty =
DependencyProperty.RegisterAttached("DoubleClickCommandParameter", typeof(object), typeof(Attached));
static void CommandChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var fe = obj as FrameworkElement;
if (e.OldValue == null && e.NewValue != null)
{
fe.AddHandler(Button.MouseDoubleClickEvent, ExecuteCommand);
}
else if (e.OldValue != null && e.NewValue == null)
{
fe.RemoveHandler(Button.MouseDoubleClickEvent, ExecuteCommand);
}
}
static void ExecuteCommand(object sender, RoutedEventArgs e)
{
var ele = sender as Button;
ICommand command = GetDoubleClickCommand(ele);
object parameter = GetDoubleClickCommandParameter(ele);
command.Execute(parameter);
}
}
警告:上面只是在网络浏览器中输入。由于缺乏良好的Minimal, Complete, and Verifiable code example,我没有费心去尝试编译,从不介意运行,以上。我相信,如果存在印刷错误或逻辑错误,它们很少,并且您可以根据自己的目标轻松了解代码实际应该是什么。
这里最重要的是我添加了Attached.DoubleClickCommandParameter
附加属性。这将允许您在命令本身的同时设置命令参数。
我还更改了其他一些实现细节:
ICommand
保存在static
字段中,因为您的实现具有它。你的代码拥有它的方式,你一次只能拥有一个命令。如果您尝试在多个元素上设置附加属性,并使用多个ICommand
值,那么您仍然只能获得最近设置的ICommand
。通过我的更改,您将始终获得您设置的命令。然后你可以在代码隐藏中使用附加属性,如下所示:
Attached.SetDoubleClickCommand(btn, ((CardManagementViewModel)values[1]).ChangeImageCommand);
Attached.SetDoubleClickCommandParameter(btn, ((CardManagementViewModel)values[1]).ChangeImageCommandParameter);
请注意,我假设您拥有一个ChangeImageCommandParameter
属性,用于存储您要发送的参数。您当然可以将属性值设置为您想要的任何值,例如引用所选项目或其他内容的值。
我还更改了设置以调用Attached
类的属性setter方法,这是对WPF中附加属性抽象的更恰当的使用。当然,在大多数实现中,它与直接调用SetValue()
方法完全相同,但最好通过附加属性的方法,以防它们以某种方式定制行为
现在,所有这一切,我将重申,你的更广泛的设计在几个不同的方面是非常错误的。通过忽略MVVM或类似的传统方法,将UI配置和行为绑定到视图模型,尤其是将转换器用作实际修改对象状态的位置,您正在创建一个系统它可能会有一些微妙的,难以发现的,几乎不可能修复的错误。
但这主要与如何使用附属财产的问题无关。即使在精心设计的WPF程序中,附加属性也有它们的位置,我希望上面的内容可以让您更好地了解如何扩展现有的附加属性,以便它支持其他值(例如CommandProperty
值)。