简体   繁体   中英

UserControl with DataContext and DependencyProperty

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM