假设如下代码,
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 中绑定(bind) ICommand”。我知道 DependencyProperties 可以像这样绑定(bind),但在这种情况下我需要绑定(bind) ICommand。
编辑
我可以使用
DataContext
SomeView
在 SomeCustomControl
.两者之间有更多我无法化解的逻辑和分离。我“必须”维护 Reload/Save ICommands
的引用在我的 SomeCustomControl
某处.
最佳答案
让我直截了本地说,你想绑定(bind)到 Reload
和 Save
对?
因此需要创建、声明和定义两个依赖属性 ReloadCommandProperty
和 SaveCommandProperty
类型 ICommand
对于 SomeCustomControl
.
所以假设 SomeCustomControl
源自 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);
}
}
}
在正确绑定(bind)到
RelodCommand
之后和 SaveCommand
属性将开始工作... <SomeCustomControl RelodCommand="{Binding ViewModelReloadCommand}"
SaveCommand="{Binding ViewModelSaveCommand}" />
关于wpf - 如何在自定义控件中创建可绑定(bind)命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7660547/