如何在自定义控件中创建可绑定命令?

Man*_*ani 20 wpf xaml binding

假设代码如下,

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 ??
Run Code Online (Sandbox Code Playgroud)

在我的SomeCustomControl中,我需要支持"在xaml中绑定ICommand".我理解DependencyProperties可以像这样绑定,但在这种情况下我需要绑定ICommand.

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

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

非常感谢.

WPF*_*-it 37

让我直截了当,你想绑定到ReloadSave对吗?

所以需要创建,声明和定义两个依赖性质ReloadCommandPropertySaveCommandProperty类型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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在这个适当的绑定RelodCommandSaveCommand属性将开始工作...

     <SomeCustomControl RelodCommand="{Binding ViewModelReloadCommand}"
                        SaveCommand="{Binding ViewModelSaveCommand}" /> 
Run Code Online (Sandbox Code Playgroud)