2017-06-12 57 views
1

我想讓可重用的慢跑用戶控件。我在主窗口中添加了usercontrol。如何通過用戶控制按鈕在父窗口上執行命令?

我要讓這樣 用戶控件按鈕點擊 - >「UpJogClickCommand」呼叫「UpJogRelayCommand」 - >執行法(UpJogMove)

但我的代碼不工作..當我點擊按鈕,主代碼做不執行 'UpJogMove'

[JogButtonControl.xaml]

<UserControl> 
    <Grid> 
     <Button Command="{Binding UpJogClickCommand}"> 
    </Grid> 
</UserControl> 

[JogButtonControl.xaml.cs]

public partial class JogButtonControl : UserControl 
{ 
    public static readonly DependencyProperty UpJogClickCommandProperty = 
     DependencyProperty.Register(
      "UpJogClickCommand", 
      typeof(ICommand), 
      typeof(JogButtonControl)); 
    public ICommand UpJogClickCommand 
    { 
     get { return (ICommand)GetValue(UpJogClickCommandProperty); } 
     set { SetValue(UpJogClickCommandProperty, value); } 
    } 
    public JogButtonControl() 
    { 
     InitializeComponent(); 
    } 
} 

[MainWindow.xaml]

<StackPanel x:Name="TempSP" Grid.Column="7"> 
    <JogControl:JogButtonControl UpJogClickCommand="{Binding Path=UpJogRelayCommand}" 
</StackPanel> 

[MainWindow.xaml.cs]

private RelayCommand<object> _upJogRelayCommand; 
public ICommand UpJogRelayCommand 
{ 
    get 
    { 
     if (_upJogRelayCommand == null) 
     { 
      _upJogRelayCommand = new RelayCommand<object>(UpJogMove); 
     } 
     return _upJogRelayCommand; 
    } 
} 
private void UpJogMove(object notUsed) 
{ 
    Debug.Print("UpJogExcuted():"); 
    MoveToUpDirection(); 
} 
+0

我沒有看到任何設置'JogButtonControl.UpJogClickCommand'屬性值的代碼。如果不是簡單地忘記設置屬性值,則需要提供可靠地再現問題的良好[mcve]。另外,要更具體地說明問題所在。這些代碼做的是什麼_exactly_,你想要什麼,你到底想要修復它,還有什麼_specifically_你還有問題。 –

回答

1

就應該在你的用戶控件,例如的XAML綁定的源對象通過設置RelativeSource屬性:

<UserControl> 
    <Grid> 
     <Button Command="{Binding UpJogClickCommand, 
          RelativeSource={RelativeSource AncestorType=UserControl}}"> 
    </Grid> 
</UserControl> 
+0

非常感謝你的工作! –

相關問題