我们使用MVVM模式。在视图中,我将save命令绑定到一个按钮:
在视图模型中,我想找出save命令绑定目标,可以吗?
private Button GetBindingControl(ICommand command)
{
// What should I do here:
return button;
}发布于 2011-10-14 10:25:24
这是不可能的,而且它违背了MVVM的目的(将UI逻辑放在VM中,而不管使用的控件是什么)
也许你可以问你想解决的是什么问题。
发布于 2011-10-14 13:33:12
正如@Diego所说,这违背了MVVM的目的,因为我们必须努力不在MVVM的视图模型中包含视觉效果或控件……
话虽如此,有两种选择……
使用RoutedCommands
RoutedCommands在MVVM中是不被允许的,因为它们需要被紧密的命令绑定到UI元素,也就是我们的例子中的按钮。因此,它们也违背了MVVM的目的。
但MVVM与附加的行为愉快地共存。
许多开发人员都回避这个极其强大的功能。我们可以将其与RoutedCommands一起使用。
在你的情况下
附加到按钮,使用action delegate.
e.Parameter字符串值相应地调用您的源。下面是示例代码...
假设您有常用的signature Action<Button, string>按钮实用程序
public static class ButtonActionUtilities
{
public static Action<Button, string> ButtonActionDelegate
{
get
{
return ExecuteButtonClick;
}
}
public static void ExecuteButtonClick(Button btn, string param)
{
MessageBox.Show(
"You clicked button " + btn.Content + " with parameter " + param);
}
}那么附加的行为如下所示。
public static class ButtonAttachedBehavior
{
public static readonly DependencyProperty ActionDelegateProperty
= DependencyProperty.RegisterAttached(
"ActionDelegate",
typeof(Action<Button, string>),
typeof(ButtonAttachedBehavior),
new PropertyMetadata(null, OnActionDelegatePropertyChanged));
public static Action<Button, string> GetActionDelegate(
DependencyObject depObj)
{
return (Action<Button, string>)depObj.GetValue(
ActionDelegateProperty);
}
public static void SetActionDelegate(
DependencyObject depObj, Action<Button, string> value)
{
depObj.SetValue(ActionDelegateProperty, value);
}
private static void OnActionDelegatePropertyChanged(
DependencyObject depObj,
DependencyPropertyChangedEventArgs e)
{
if (depObj is Button
&& e.NewValue is Action<Button, string>)
{
((Button)depObj).Command
= new RoutedCommand(
"ActionRoutedCommand",
typeof(ButtonAttachedBehavior));
((Button) depObj).CommandBindings.Add(
new CommandBinding(
((Button) depObj).Command,
OnActionRoutedCommandExecuted));
}
}
private static void OnActionRoutedCommandExecuted(
object sender, ExecutedRoutedEventArgs e)
{
var actionDelegate = GetActionDelegate((Button)e.Source);
actionDelegate((Button) e.Source, (string)e.Parameter);
}
}在XAML上,它将看起来像这样……
<StackPanel>
<Button x:Name="TestButton" Content="Test Me"
local:ButtonAttachedBehavior.ActionDelegate
="{x:Static local:ButtonActionUtilities.ButtonActionDelegate}"
CommandParameter
="{Binding Text, ElementName=ParameterTextBox}"/>
<TextBox x:Name="ParameterTextBox"/>
</StackPanel>因此,使用上面的代码,您只需要将ActionDelegate attached属性设置为approapriate委托,它就会执行该委托。
我仍然建议您修改现有的代码设置,以分离特定于按钮的行为,使其更加友好。
https://stackoverflow.com/questions/7762331
复制相似问题