【问题标题】:UserControl with DataContext and DependencyProperty具有 DataContext 和 DependencyProperty 的 UserControl
【发布时间】: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


【解决方案1】:

您必须将 Binding 的源对象设置为 UserControl,例如像这样:

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

【讨论】:

    猜你喜欢
    • 2011-06-29
    • 2015-02-16
    • 1970-01-01
    • 2014-05-03
    • 2012-03-02
    • 1970-01-01
    • 2012-06-06
    • 2011-07-01
    • 1970-01-01
    相关资源
    最近更新 更多