如何通过用户控制按钮在父 window 上执行命令?

How to execute command on parent window by User control button?

我想制作可重复使用的点动用户控件。我在主要 window.

上添加了用户控件

我想做成这样 单击用户控件按钮 -> '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();
}

您应该在 UserControl 的 XAML 中指定绑定的源对象,例如通过设置 RelativeSource 属性:

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