How to use command bindings in user controls in wpf?

前端 未结 2 574
一个人的身影
一个人的身影 2021-02-04 16:13

In MainWindow the commandbinding works fine. In UserControl1 it doesnt work. Note the datacontext is set correctly as is evidenced by the content of the button which is the res

2条回答
  •  生来不讨喜
    2021-02-04 16:35

    It's the best solution:

     
            
     
    

    Other solutions:

    You forgot set DataContext to UserControl1.

      public UserControl1()
            {
                InitializeComponent();
                ClickHereCommand = new RoutedCommand();
                CommandBindings.Add(new CommandBinding(ClickHereCommand, ClickHereExecuted));
                ButtonContent = "Click Here";
                this.DataContext = this;
            }
    

    And after this you must delete in UserControl1 DataContext in Grid.

    This:

    
        
    
    

    you must change to this:

    
            
    
    

    Solution without set DataContext in UserControl:

    You must change ButtonContent and ClickHereCommand to DependencyProperty.

            public string ButtonContent
            {
                get { return (string)GetValue(ButtonContentProperty); }
                set { SetValue(ButtonContentProperty, value); }
            }
    
            public static readonly DependencyProperty ButtonContentProperty =
                DependencyProperty.Register("ButtonContent", typeof(string), typeof(UserControl1), new UIPropertyMetadata(string.Empty));
    
            public RoutedCommand ClickHereCommand
            {
                get { return (RoutedCommand)GetValue(ClickHereCommandProperty); }
                set { SetValue(ClickHereCommandProperty, value); }
            }
    
            public static readonly DependencyProperty ClickHereCommandProperty =
                DependencyProperty.Register("ClickHereCommand", typeof(RoutedCommand), typeof(UserControl1), new UIPropertyMetadata(null));
    

    And in ctor of UserControl1:

     public UserControl1()
        {
            InitializeComponent();
    
            ClickHereCommand = new RoutedCommand();
            CommandBindings.Add(new CommandBinding(ClickHereCommand, ClickHereExecuted));            
            ButtonContent = "Click Here";
            //this.DataContext = this;
        }
    

提交回复
热议问题