1
votes

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
Why do you need this DataContext = this? Control can have only one DataContext. Either one with SelectedPerson or set manually by youdkozl
I've removed it, but still same problemStruct
When you say "it has no effect" you probably mean that the property setter in code behind isn't called. That is because WPF directly calls the SetValue method (and thus bypasses the setter) when the property is set in XAML or by a binding (or some other inputs). You'll have to register a PropertyChangedCallback with the FrameworkPropertyMetadata. That said, you don't need to implement INotifyPropertyChanged for a dependency property.Clemens
How are you using your dependency property in the user control's xaml?Janne Matikainen
I know that the setter isn't called, but it has no effect in my user control. I've edited the question with the code of the user controlStruct

1 Answers

2
votes

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}}" />