wpf - 如何在自定义控件中创建可绑定(bind)命令?

标签 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 ??
在我的 SomeCustomControl 中,我需要支持“在 xaml 中绑定(bind) ICommand”。
我知道 DependencyProperties 可以像这样绑定(bind),但在这种情况下我需要绑定(bind) ICommand。
编辑
我可以使用 DataContext SomeViewSomeCustomControl .两者之间有更多我无法化解的逻辑和分离。我“必须”维护 Reload/Save ICommands 的引用在我的 SomeCustomControl 某处.

最佳答案

让我直截了本地说,你想绑定(bind)到 ReloadSave对?

因此需要创建、声明和定义两个依赖属性 ReloadCommandPropertySaveCommandProperty类型 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/

相关文章:

c# - 如何在 GridView 上添加静态项目?

c# - 使用 StringFormat 在值中间添加单词

c# - 使用 caliburn micro 在弹出控件中绑定(bind) UserControl

binding - 将 Mvvmcross 绑定(bind)与 MonoTouch.Dialog(列表和命令)结合使用

.net - 样式不适用于 Win7 x32 (.Net 4.0)

wpf - 如何在 WPF 中实现虚线或点线边框?

c# - Visual Studio 2015 WPF XAML 编辑器无法打开 XAML 文件

c# - 为什么无法识别或访问 "<ControlTemplate.Triggers>"?

c# - 在 TreeView 中显示 "root"节点

c# - 将一个类绑定(bind)到多个接口(interface)作为单例