2010-05-05 103 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