问题
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