假设下面的代码,

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。

有人可以建议什么是最好的方法吗?
任何建议的 Material 或链接都将有用,因为我错过了方向。

编辑1)我可以在SomeCustomControl中使用DataContext SomeView。两者之间还有更多我无法解决的逻辑和分离。我必须在SomeCustomControl中的某个地方维护对Reload / Save ICommands的引用。

非常感谢。

最佳答案

让我直接告诉您,您想绑定(bind)到ReloadSave对吗?

因此,需要为ReloadCommandProperty创建,声明和定义两个类型为SaveCommandProperty的依赖项属性ICommandSomeCustomControl

所以假设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)到RelodCommandSaveCommand属性后,将开始工作...
     <SomeCustomControl RelodCommand="{Binding ViewModelReloadCommand}"
                        SaveCommand="{Binding ViewModelSaveCommand}" />

10-07 20:00
查看更多