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

时间:2017-06-12 07:24:52

标签: c# wpf binding user-controls command

我想制作可重复使用的慢跑用户控件。我在主窗口上添加了usercontrol。

我想这样做 单击usercontrol按钮 - > 'UpJogClickCommand'调用'UpJogRelayCommand' - > execute方法(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();
}

1 个答案:

答案 0 :(得分:1)

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

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