c# - 标准属性有效,但依赖属性在 WPF 中无效

标签 c# wpf xaml

我有下面的代码,它可以工作:

public DataTemplate ItemTemplate
{
    get { return _list.ItemTemplate; }
    set { _list.ItemTemplate = value; }
}

我有我想要的代码,但它不起作用。甚至永远不会调用 setter:

public static readonly DependencyProperty ItemTemplateProperty = DependencyProperty.Register("ItemTemplate", typeof(DataTemplate), typeof(MyUserControl));
public DataTemplate ItemTemplate
{
    get { return (DataTemplate)GetValue(ItemTemplateProperty); }
    set
    {
        _list.ItemTemplate = value;
        SetValue(ItemTemplateProperty, value);
    }
}

在 XAML 中使用它:

<Window.Resources>
    <DataTemplate x:Key="ItemTemplate">
        <TextBlock Text="{Binding Path=Name}"/>
    </DataTemplate>
</Window.Resources>

<local:MyUserControl ItemTemplate="{StaticResource ItemTemplate}"/>

为什么标准属性有效而依赖属性无效?

最佳答案

对于依赖属性,.Net 做了一些不明显的事情:它直接访问由 ItemTemplateProperty 标识的依赖属性,而不是使用 getset 您声明的方法。在这种情况下,唯一的区别是您的 _list.ItemTemplate = value; 永远不会运行。

当您使用依赖属性时,您的 getter 和 setter should only contain the usual things .其他任何内容最终都会造成混淆,因为 WPF 在使用该属性时会绕过它们。

如果您需要将 _list.ItemTemplate 设置为该值,您应该附加一个静态 PropertyChangedCallback使用 other DependencyProperty.Register overload .例如

private static void OnItemTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
    var uc = (MyUserControl)d;
    uc._list.ItemTemplate = (DataTemplate)e.NewValue;
}

关于c# - 标准属性有效,但依赖属性在 WPF 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17925046/

相关文章:

c# - 如何在我的工具提示上获得更厚的阴影?

XAML 数据网格数据模板

C# Windows 通用应用程序 ListView 所选项目内容

c# - SendMessage 不启动函数 (HoloLens/Unity/C#)

c# - 打印多个 datagridview 页面

c# - 更改图钉 WPF 的图像

wpf - WPF 中 ToggleButton 的 IsChecked 属性的 OneWay 绑定(bind)

c# - 覆盖重叠方法

c# - 我想等待抛出 AggregateException,而不仅仅是第一个异常

.net - 对象的索引器是否可以通过其 TypeDescriptor 以某种方式访问​​?