WPF UserControls - 在UserControl内的按钮上设置.Command属性 [英] WPF UserControls - setting the .Command property on button inside UserControl

查看:1617
本文介绍了WPF UserControls - 在UserControl内的按钮上设置.Command属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UserControl包含一个按钮和一些其他控件:

I've got a UserControl that contains a button and some other controls:

<UserControl>
  <StackPanel>
     <Button x:Name="button" />
     ...
  </StackPanel>
</UserControl>

当我创建一个新的控件的实例,我想得到Button的Command属性: / p>

When I create a new instance of that control, I want to get at the Button's Command property:

<my:GreatUserControl TheButton.Command="{Binding SomeCommandHere}">
</my:GreatUserControl>

当然,TheButton.Command的东西不工作。

Of course, the "TheButton.Command" thing doesn't work.

所以我的问题是:使用XAML,如何在用户控件中设置按钮的.Command属性?

So my question is: Using XAML, how can I set the .Command property of the button inside my user control?

推荐答案

向UserControl添加依赖属性,并将按钮的Command属性绑定到该属性。

Add a dependency property to your UserControl and bind the button's Command property to that.

所以在你的GreatUserControl:

So in your GreatUserControl:

public ICommand SomeCommand
{
    get { return (ICommand)GetValue(SomeCommandProperty); }
    set { SetValue(SomeCommandProperty, value); }
}

public static readonly DependencyProperty SomeCommandProperty =
    DependencyProperty.Register("SomeCommand", typeof(ICommand), typeof(GreatUserControl), new UIPropertyMetadata(null));

在您的GreatUserControl的XAML中:

And in your GreatUserControl's XAML:

<UserControl 
    x:Class="Whatever.GreatUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="me"
    >
    <Button Command="{Binding SomeCommand,ElementName=me}">Click Me!</Button>
</UserControl>

因此,您的按钮绑定到UserControl本身上的命令。现在您可以在父窗口中设置:

So your button binds to the command on the UserControl itself. Now you can set that in your parent window:

<my:GreatUserControl SomeCommand="{Binding SomeCommandHere}" />

这篇关于WPF UserControls - 在UserControl内的按钮上设置.Command属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆