WPF命令绑定自定义UserControl

时间:2014-11-01 04:45:58

标签: c# wpf commandbinding

我有一个自定义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属性,但Type应该Command是什么?我做了一些搜索,似乎有很多可能性:RoutedUICommandRoutedCommandCommandBindingDelegateCommand等,我很遗憾。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

绑定到Command DependencyProperty的任何对象都必须实现ICommand interface。我的建议是,如果你要做的就是使用命令来捕获和处理按钮的点击输入,那就是使用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所具有的所有其他属性。