【发布时间】:2016-04-21 10:44:54
【问题描述】:
我想将 DependencyProperty 和 DataContext 绑定到我的 UserControl。 DataContext 正在工作,但设置 DependencyProperty 无效。这是我的用户控件:
<MyProperty:MyPropertyControl DataContext="{Binding SelectedPerson}" IsEnabled="True"/>
这是我的 UserControl 的 CodeBehind:
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}" />
【问题讨论】:
-
你为什么需要这个
DataContext = this?控件只能有一个DataContext。要么是SelectedPerson,要么是你手动设置 -
我已经删除了,但还是一样的问题
-
当你说“它没有效果”时,你可能意味着后面代码中的属性设置器没有被调用。这是因为当在 XAML 中或通过绑定(或某些其他输入)设置属性时,WPF 直接调用 SetValue 方法(因此绕过设置器)。您必须使用 FrameworkPropertyMetadata 注册 PropertyChangedCallback。也就是说,您不需要为依赖属性实现 INotifyPropertyChanged。
-
你是如何在用户控件的 xaml 中使用你的依赖属性的?
-
我知道 setter 没有被调用,但它对我的用户控件没有影响。我已经用用户控件的代码编辑了问题
标签: c# .net wpf xaml dependency-properties