WPF无法让命令和依赖属性一起工作,或者我只是错误地使用它们?

我创建了一个wpf应用程序,我添加了一个用户控件和一个自定义控件.自定义控件在用户控件中使用(计划用于许多其他类型的用户控件).

举一个简单的例子,自定义控件有一个属性为Brush的依赖属性,标题为backgroundcolour,然后在defualt模板中设置自定义控件作为边框的背景.我的想法是,我可以使用Command和CommandParameter属性从用户控件设置此值.正如我在下面尝试做的那样

用户控件xaml(TestControl是自定义控件)

<Grid>
    <Grid.Resources>
        <MyNamespace:EditColourCommand x:Key="EditColour"/>
    </Grid.Resources>

    <Grid.ContextMenu>
        <ContextMenu>
            <MenuItem Name="Test" 
                      Header="Test" 
                      Command="{StaticResource EditColour}" 
                      CommandParameter="{Binding ElementName=testControl1,Path=BackgroundColour,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
        </ContextMenu>
    </Grid.ContextMenu>

    <MyNamespace:TestControl HorizontalAlignment="Left" 
                             Margin="213,90,0" 
                             x:Name="testControl1" 
                             VerticalAlignment="Top" 
                             Height="77" 
                             Width="230"/>

</Grid>

我的自定义控制代码:

public class TestControl : Control
{
    static TestControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(TestControl),new FrameworkPropertyMetadata(typeof(TestControl)));
    }

    public static DependencyProperty BackgroundColourProperty = 
        DependencyProperty.Register("BackgroundColour",typeof(Brush),typeof(TestControl),new PropertyMetadata(Brushes.Blue,BackgroundColourPropertyChangedHandler));

    public Brush BackgroundColour
    {
        get
        {
            return (Brush)GetValue(BackgroundColourProperty);
        }
        set
        {
            SetValue(BackgroundColourProperty,value);
        }
    }

    public static void BackgroundColourPropertyChangedHandler(DependencyObject sender,DependencyPropertyChangedEventArgs e)
    {
    } 
}

最后,The Command

public class EditColourCommand : ICommand
{
    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        parameter = Brushes.Black;
    }
}

该命令被触发并且它具有defualt值,在这种情况下蓝色作为参数,但它从不将值设置为黑色.有人能把我推向正确的方向吗?

解决方法

只需将命令修改为

CommandParameter="{Binding ElementName=testControl1}"

并修改您的命令执行到

public void Execute(object parameter)
{
    var ctrl = parameter as TestControl 
    ctrl.BackgroundColour = Brushes.Black;
}

你不能指望绑定像你在CommandParameter中那样工作.

相关文章

什么是设计模式一套被反复使用、多数人知晓的、经过分类编目...
单一职责原则定义(Single Responsibility Principle,SRP)...
动态代理和CGLib代理分不清吗,看看这篇文章,写的非常好,强...
适配器模式将一个类的接口转换成客户期望的另一个接口,使得...
策略模式定义了一系列算法族,并封装在类中,它们之间可以互...
设计模式讲的是如何编写可扩展、可维护、可读的高质量代码,...