具有 DataContext 和 DependencyProperty 的 UserControl
UserControl with DataContext and DependencyProperty
我想将 DependencyProperty 和 DataContext 绑定到我的 UserControl。 DataContext 正在运行,但设置 DependencyProperty 无效。这是我的用户控件:
<MyProperty:MyPropertyControl DataContext="{Binding SelectedPerson}" IsEnabled="True"/>
这是我的 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");
}
}
我可以将 属性 IsEnabled 设置为 true 或 false,但没有任何效果。
用户控制代码:
<Button Content="Test" Width="100" Height="30" IsEnabled="{Binding IsEnabled}" />
您必须将绑定的源对象设置为 UserControl,例如像这样:
<Button ... IsEnabled="{Binding IsEnabled,
RelativeSource={RelativeSource AncestorType=UserControl}}" />
我想将 DependencyProperty 和 DataContext 绑定到我的 UserControl。 DataContext 正在运行,但设置 DependencyProperty 无效。这是我的用户控件:
<MyProperty:MyPropertyControl DataContext="{Binding SelectedPerson}" IsEnabled="True"/>
这是我的 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");
}
}
我可以将 属性 IsEnabled 设置为 true 或 false,但没有任何效果。
用户控制代码:
<Button Content="Test" Width="100" Height="30" IsEnabled="{Binding IsEnabled}" />
您必须将绑定的源对象设置为 UserControl,例如像这样:
<Button ... IsEnabled="{Binding IsEnabled,
RelativeSource={RelativeSource AncestorType=UserControl}}" />