命令属性公开在UserControl中不起作用

时间:2015-02-01 09:41:53

标签: wpf mvvm data-binding

我有一个包装按钮的UserControl:

<UserControl x:Class="MyProject.Controls.BigButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d"
             DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Button Command="{Binding Command}">
        <StackPanel HorizontalAlignment="Center" Margin="5">
            <ContentPresenter Width="40" Height="40" Margin="0,0,0,5" Content="{Binding Icon}" />
            <TextBlock TextAlignment="Center" TextWrapping="Wrap" Text="{Binding Text}"></TextBlock>
        </StackPanel> 
    </Button>
</UserControl>

它公开了代码隐藏文件中的一些属性:

public partial class BigButton : UserControl
{
    public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(BigButton));
    public string Text 
    {
        get { return (string) GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

    public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(UIElement), typeof(BigButton));
    public UIElement Icon
    {
        get { return (UIElement)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

    public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(BigButton));
    public ICommand Command
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }

    public BigButton()
    {
        InitializeComponent();
    }
}

然后我以这种方式将此控件添加到视图中:

<controls:BigButton
    Icon="{StaticResource IconStop}"
    Text="Stop"
    Command="{Binding StopCommand}" />

并不是该死的执行命令。图标已就位以及文本,因此至少有一些公开的属性正常工作。但命令并非如此。命令本身似乎很好,我可以使用

执行它
<Button Command="{Binding StopCommand}" />

所以我想知道,我做错了什么?

1 个答案:

答案 0 :(得分:0)

默认情况下,您的BigButton会继承父级的DataContext,但您明确将其设置为自身:

 DataContext="{Binding RelativeSource={RelativeSource Self}}"

因为当你设置

Command="{Binding StopCommand}"

它开始在BigButton的DataContext中寻找,因此没有找到任何结果应该在Output中反映为错误消息。解决方案是通过设置:

来访问父级的DataContext
<Button Command="{Binding Command}" Name="MyButton">

   public BigButton()
        {
            InitializeComponent();
            this.MyButton.DataContext = this;
        }

我推荐你article