UserControl与DataContext和DependencyProperty

时间:2016-01-15 18:55:02

标签: c# .net wpf xaml dependency-properties

我想将DependencyProperty和DataContext绑定到我的UserControl。 DataContext正在运行,但设置DependencyProperty无效。这是我的UserControl:

<MyProperty:MyPropertyControl DataContext="{Binding SelectedPerson}" IsEnabled="True"/>

这是我的UserControl的CodeBehind:

public static readonly DependencyProperty IsEnabledProperty =
    DependencyProperty.Register(
    "IsEnabled",
    typeof(Boolean),
    typeof(MyProperty:MyPropertyControl),
    new FrameworkPropertyMetadata()
    {
        DefaultValue = false,
        BindsTwoWayByDefault = false,
        DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
    });


public MyPropertyControl()
{
    InitializeComponent();
}

public Boolean IsEnabled
{
    get { return (Boolean)GetValue(IsEnabledProperty);  }
    set
    {
        SetValue(IsEnabledProperty, value);
        NotifyPropertyChanged("IsEnabled");
    }
}

我可以将属性IsEnabled设置为true或false,但它没有效果。

用户控制代码:

<Button Content="Test" Width="100" Height="30" IsEnabled="{Binding IsEnabled}" />

1 个答案:

答案 0 :(得分:1)

您必须将Binding的源对象设置为UserControl,例如像这样:

<Button ... IsEnabled="{Binding IsEnabled,
                        RelativeSource={RelativeSource AncestorType=UserControl}}" />