2010-05-05 99 views
9

我有一个包含一个按钮和一些其他控件的用户控件:WPF用户控件 - 设置.Command财产上的按钮内部用户控件

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

当我创建控件的新实例,我想得到按钮的命令属性:

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

当然,“TheButton.Command”的东西不起作用。

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

回答

18

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

所以在你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:

<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> 

所以您的按钮结合对用户控件本身的命令。现在你可以在你的父窗口中设置:

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

谢谢,马特。我意识到部分方法可以通过注册DependencyProperty来实现,但我希望有一种更简单的方法(例如,可以将Button作为控件的属性公开),然后将其设置在XAML中。无论如何。这会做。感谢你的回答。 – 2010-05-06 14:05:00

+3

当您将DataContext添加到您的用户控件时,这会中断。 – Nicholas 2011-02-16 22:27:54

+10

患者:“当我这样做时会感到疼痛。”医生:“停止这样做。” – 2011-02-16 22:37:31