如何在自定义控件中创建可绑定的命令? [英] How to create bindable commands in Custom control?
问题描述
假设下面的代码,
public class SomeViewModel{
ICommand ReloadCommand{get...}
ICommand SaveCommand{get..}
}
//SomeView.xaml
<SomeCustomControl Reload="ReloadCommand" Save="SaveCommand" /> //NOT SURE HOW??
//SomeCustomContro.xaml
<SomeCustomControl x:Name="someCustomControl">
<Button Command={Binding ElementName=someCustomControl, Path=Reload />
<Button Command={Binding ElementName=someCustomControl, Path=Save />
</SomeCustomControl>
//SomeCustomControl.xaml.cs
..... //NOT SURE HOW TO ALLOW BINDING TO A ICOMMAND ??
在我的SomeCustomControl中,我需要支持在xaml中绑定ICommand". 我知道DependencyProperties可以这样绑定,但是在这种情况下,我需要绑定ICommand.
In my SomeCustomControl, I need to support "binding of ICommand in xaml". I understand DependencyProperties could be bind like this, but in this case I need to bind ICommand.
有人可以建议这样做的最好方法是什么? 任何建议的材料或链接都将有用,因为我错过了方向.
Can somebody please suggest what is the best way to do this? Any suggested material or link would be of use because I am missing a direction.
编辑1)我可以在SomeCustomControl中使用DataContext SomeView.两者之间还有更多我无法解决的逻辑和分离.我必须在SomeCustomControl中的某个位置维护对Reload/Save ICommands的引用.
EDIT 1) I can use the DataContext SomeView in SomeCustomControl. There is more logic and separation between the two which I can not dissolve. I 'must' maintain a reference of Reload/Save ICommands somewhere in my SomeCustomControl.
非常感谢.
推荐答案
让我直截了当,您想绑定到Reload
和Save
对吗?
Let me get you straight, you want to bind to the Reload
and Save
right?
因此需要为SomeCustomControl
创建,声明和定义两个类型为ICommand
的依赖项属性ReloadCommandProperty
和SaveCommandProperty
.
So that needs creating, declaring and defining two dependency properties ReloadCommandProperty
and SaveCommandProperty
of type ICommand
for SomeCustomControl
.
因此,假设SomeCustomControl
来自Control
...
So assuming that SomeCustomControl
derives from Control
...
public class SomeCustomControl : Control
{
public static DependencyProperty ReloadCommandProperty
= DependencyProperty.Register(
"ReloadCommand",
typeof (ICommand),
typeof (SomeCustomControl));
public static DependencyProperty SaveCommandProperty
= DependencyProperty.Register(
"SaveCommand",
typeof(ICommand),
typeof(SomeCustomControl));
public ICommand ReloadCommand
{
get
{
return (ICommand)GetValue(ReloadCommandProperty);
}
set
{
SetValue(ReloadCommandProperty, value);
}
}
public ICommand SaveCommand
{
get
{
return (ICommand)GetValue(SaveCommandProperty);
}
set
{
SetValue(SaveCommandProperty, value);
}
}
}
正确绑定到RelodCommand
和SaveCommand
属性后,将开始工作...
After this proper binding to RelodCommand
and SaveCommand
properties will start working...
<SomeCustomControl RelodCommand="{Binding ViewModelReloadCommand}"
SaveCommand="{Binding ViewModelSaveCommand}" />
这篇关于如何在自定义控件中创建可绑定的命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!