繁体   English   中英

用于自定义UserControl的WPF命令绑定

[英]WPF command binding for custom UserControl

我有一个自定义Button ,如下所示:

<UserControl...>
    <Button HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="3*"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>

            <Viewbox Stretch="Uniform" Grid.Column="0">
                <TextBlock x:Name="numCopyTB" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=Text}"/>
            </Viewbox>
            <Viewbox Grid.Column="1">
                <TextBlock Style="{StaticResource updownBlock}"/>
            </Viewbox>

        </Grid>
    </Button>
</UserControl>

在后面的代码中,我添加了其Text属性。 后面的代码如下:

public partial class UpdownButton : UserControl
{

    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(UpdownButton));

    public UpdownButton()
    {
        InitializeComponent();
    }

    public string Text
    {
        get { return GetValue(TextProperty) as string; }
        set { SetValue(TextProperty, value); }
    }
}

我正在学习CommandBinding并且希望能够执行类似<local:MyCustomButton Command="{Binding MethodName}"/>

似乎我需要在代码后面添加Command属性,但是Command应该是什么Type 我进行了一些搜索,似乎有很多可能: RoutedUICommandRoutedCommandCommandBindingDelegateCommand等,我很迷路。 任何帮助表示赞赏!

绑定到Command DependencyProperty的任何对象都必须实现ICommand接口 我的建议是,如果您要使用的命令是捕获并处理对按钮的单击输入,则建议使用RelayCommand设计的实现。 这将允许您在ViewModel中创建RelayCommand的实例:

public RelayCommand yourCustomButtonCommand { get; set; }

然后在您的构造函数中,实例化RelayCommand,如下所示:

MyCommand = new RelayCommand( 
ExecuteMyCommand, 
() => _canExecuteMyCommand); 

其中ExecuteMyCommand是您希望每次单击Button时要执行的方法,而_canExecuteMyCommand是一个谓词,它确定在任何给定时间点是否应单击按钮。

根据您的问题,以下是如何在背后的代码中从Button继承的方法:

public partial class UpdownButton : Button
{
    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(UpdownButton));

    public UpdownButton()
    {
        InitializeComponent();
    }

    public string Text
    {
        get { return GetValue(TextProperty) as string; }
        set { SetValue(TextProperty, value); }
    }
}

这将产生一个对象,该对象继承Button的所有依赖项属性,并具有您在上面定义的新属性。 要记住的最重要的一点是,必须将用户控件中XAML的顶级类型更改为<Button> ,而不是<UserControl>

进行了这些更改之后,您的UpdownButton现在将具有Command属性以及Button的所有其他属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM