我创建了一个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中那样工作.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。