WPF-用户控件之间的命令

时间:2018-07-02 08:08:21

标签: wpf

我想将命令绑定到我的用户控件:

<MyUserControl MyCommand="{Binding TestCommand}"/>

MyUserControl.xaml.cs

public partial class MyUserControl: UserControl
    {
        public ICommand MyCommand
        {
            get => (ICommand)GetValue(MyCommandProperty);
            set => SetValue(MyCommandProperty, value);
        }

        public static readonly DependencyProperty MyCommandProperty
            = DependencyProperty.Register("MyCommand", typeof(ICommand), typeof(UserControl), new PropertyMetadata(null));


        public MyUserControl()
        {
            InitializeComponent();
        }
    }

MyUserControl.xaml

<Button Content="CLICK" 
                Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=MyCommand}"/>

父用户控件:

 <view:MyUserControl Grid.Row="0" Grid.Column="1" MyCommand="{Binding TestCommand}"/>

当我单击按钮时,命令不执行。感谢您的建议

1 个答案:

答案 0 :(得分:0)

我试图重现此问题,但我不能,我的发现是您有时会缺少数据上下文。

MainWindow

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            testCommand = new RelayCommand(ChangeCanExecute);
            this.DataContext = this;
        }

        private ICommand testCommand { get; set; }
        private bool canExecute = true;
        public bool CanExecute
        {
            get
            {
                return this.canExecute;
            }

            set
            {
                if (this.canExecute == value)
                {
                    return;
                }

                this.canExecute = value;
            }
        }

        public ICommand TestCommand
        {
            get
            {
                return testCommand;
            }
            set
            {
                testCommand = value;
            }
        }
        public void ChangeCanExecute(object obj)
        {
            canExecute = !canExecute;
        }
    }