代码之家  ›  专栏  ›  技术社区  ›  Judah Gabriel Himango

WPF UserControls-在UserControl内的按钮上设置.Command属性

  •  10
  • Judah Gabriel Himango  · 技术社区  · 16 年前

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

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

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

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

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

    1 回复  |  直到 16 年前
        1
  •  21
  •   Matt Hamilton    16 年前

    向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));
    

    <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本身上的命令。现在可以在父窗口中设置:

    <my:GreatUserControl SomeCommand="{Binding SomeCommandHere}" />
    
    推荐文章