0

I tried to implement something earlier this afternoon and have not been able to get it working the way I want.

If I have some XAML like the following (I know it is not complete but it is for illustrative purposes only)...

<Window>
  <StackPanel>
    <Button />
    <UserControl1>
  </StackPanel>
</Window>

...and UserControl1 exposes a command property (currently, I am using a RelayCommand for this), how do I bind the Button in the Window to this command. I tried to expose a property in the Window that is bound to the command property in UserControl1 so that I could turn around and re-bind this to the Button but the property in the Window is always null. This pattern seems to work for another property (an integer value). Is there a better way to do this? Is there something with the command that prevents this from occuring?

4

1 に答える 1

1

(1) コマンドを DepenedecyProperty として定義し、実装します。

(2) ボタンの Command プロパティを UserControl の MyCommand プロパティにバインドします。

 public Class UserControl1 : UserControl 
 {

      public UserControl1()
      {
          MyCommad = new RelayCommand
                     (
                         () => { // do some stuff in execute delegate},
                         () => { return true ;}                                                        
                     );
      }

      public bool MyCommand
      {
           get { return (ICommand)GetValue(MyCommandProperty); }
           set { SetValue(MyCommandProperty, value); }
      }    

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

 }

xaml:

 <Window>
      <StackPanel>
          <Button Command={Binding ElementName=control1,Path=MyCommand,Mode=OneWay/>
          <UserControl1 x:Name="control1" />
      </StackPanel>
 </Window>
于 2012-10-10T22:07:12.630 に答える