WPF - 自定义控件 + ICommand(如何实现)?

mic*_*ael 3 wpf custom-controls routed-commands icommand

基本上,我有一个自定义控件FooControl

public class FooControl : ItemsControl
{
    //Code
}
Run Code Online (Sandbox Code Playgroud)

我需要添加一些事件处理,但我更喜欢使用 Commanding,而不是使用 RoutedEvent。但我不太确定如何去做这件事。如果我想要它,那么当 Bar1Property (DependencyProperty) 更改时,它会引发 Execute 关联的执行属性。我通过 .NET Reflector 查看了 ButtonBase 代码,哇,这看起来太复杂了。添加命令这么复杂吗?显然,我还必须做到这一点,以便我的控件根据 CanExecuteChanged 是否更改来启用/禁用其自身的某些部分。但我想那是另一部分。

这是到目前为止我的 OnBar1Changed 函数......

    private static void OnBar1Changed(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        FooControl element = (FooControl)obj;
        //What to do here?
    }
Run Code Online (Sandbox Code Playgroud)

Mat*_*est 5

听起来您提出问题的方式似乎是您希望在自定义控件中支持命令(例如按钮支持)。为此,我建议您查看 ICommandSource 的实现方式。Microsoft 提供了有关如何自行实现它的精彩演练:

http://msdn.microsoft.com/en-us/library/ms748978.aspx