如何找到 ICommand 绑定目标(控件)
我们使用MVVM模式。在视图中,我将保存命令绑定到按钮:
在视图模型中,我想找出保存命令绑定目标,可以吗?
private Button GetBindingControl(ICommand command)
{
// What should I do here:
return button;
}
We use the MVVM pattern. In the View, I have binding the save command to a button:
In the view model, I would like to find out the save command binding target, does it possible?
private Button GetBindingControl(ICommand command)
{
// What should I do here:
return button;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是不可能的,而且它违背了 MVVM 的目的(无论使用什么控件,都在 VM 中保留 UI 逻辑)
也许您可以问您要解决的问题是什么。
It's not possible, and it defeats the purpose of MVVM (having the UI logic in the VM regardless of the controls used)
Maybe you could ask instead what problem you are trying to solve.
正如 @Diego 所说,这违背了 MVVM 的目的,因为我们必须努力不在 MVVM 的视图模型中包含视觉效果或控件...
话虽如此,有两个选项...
RoutedCommands 在 MVVM 中不容易被允许,因为它们需要将命令紧密绑定到 UI 元素,即在我们的例子中为 Button。因此它们也违背了 MVVM 的目的。
但 MVVM 很高兴与附加行为共存。
许多开发人员回避这个极其强大的功能。我们可以将它与 RoutedCommands 一起使用。
在您的情况下
e.Parameter
字符串值。下面的示例代码...
假设您有签名
Action
的常见按钮实用程序,那么附加的行为如下...
在 XAML 上它将如下所示
...使用上面的代码,您只需将
ActionDelegate
附加属性设置为适当的委托,它就会执行该委托。我仍然建议您修改现有的代码设置,以分离按钮特定的行为,使其对 MVVM 更加友好。
As @Diego said, this defats the purpose of MVVM because we must try hard not to include visuals or controls in the view models in MVVM...
Having said that there are two options...
RoutedCommands are not readily allowed in MVVM as they need to be closely command bound to the UI element i.e. in our case the Button. Hence they too defeat the purpose of MVVM.
But MVVM happily co-exists with the Attached Behaviors.
Many developers shy away from this immensely powerful feature. And we can use it along with RoutedCommands.
In your case
e.Parameter
string value.Sample code below...
Assume you have common button utilities of signature
Action<Button, string>
Then the attched behavior is as below...
And on XAML it will look like this....
So with the code above you will need to just set the
ActionDelegate
attached property to approapriate delegate and it will execute that.I would still suggest you to revamp your existing code setup to separate button specific behaviors to make it more MVVM friendly.