我创建了一个wpf应用程序,我添加了一个用户控件和一个自定义控件.自定义控件在用户控件中使用(计划用于许多其他类型的用户控件). 举一个简单的例子,自定义控件有一个属性为Brush的
举一个简单的例子,自定义控件有一个属性为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,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中那样工作.
