UserControl with DataContext and DependencyProperty

孤街浪徒 提交于 2020-01-06 18:08:55

问题


I want to bind a DependencyProperty and DataContext to my UserControl. DataContext is working, but Setting the DependencyProperty has no effect. This is my UserControl:

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

And this is the CodeBehind of my UserControl:

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");
    }
}

I can set the property IsEnabled to true or false, but it has no effect.

User Control Code:

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

回答1:


You'll have to set the source object of the Binding to the UserControl, e.g. like this:

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


来源:https://stackoverflow.com/questions/34817860/usercontrol-with-datacontext-and-dependencyproperty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!