如何在自定义控件中创建可绑定命令?
假设如下代码,
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。
编辑
我可以在 SomeCustomControl
中使用 DataContext
SomeView
。两者之间有更多的逻辑和分离,我无法消除。我“必须”在我的 SomeCustomControl
中的某处维护重新加载/保存 ICommands
的引用。
Assuming a code like below,
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 ??
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.
EDIT
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
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(2)
创建一个将返回您的命令的属性,并在需要的地方绑定该属性。
private ICommand _reloadCommand;
public ICommand ReloadCommand
{
get
{
if(_reloadCommand == null) _reloadCommand = CreateReloadCommand();
return _reloadCommand;
}
}
将代码中的绑定更改为“
<Button Command={Binding ReloadCommand}" />
并将自定义控件 DataContext 绑定到包含命令的视图模型”。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
让我直接告诉你,你想绑定到
Reload
和Save
对吗?因此,需要为
SomeCustomControl
创建、声明和定义两个ICommand
类型的依赖属性ReloadCommandProperty
和SaveCommandProperty
。因此,假设
SomeCustomControl
派生自Control
...在正确绑定到
RelodCommand
和SaveCommand
属性之后将开始工作...Let me get you straight, you want to bind to the
Reload
andSave
right?So that needs creating, declaring and defining two dependency properties
ReloadCommandProperty
andSaveCommandProperty
of typeICommand
forSomeCustomControl
.So assuming that
SomeCustomControl
derives fromControl
...After this proper binding to
RelodCommand
andSaveCommand
properties will start working...