【问题标题】:Dependency Property optimisation?依赖属性优化?
【发布时间】:2016-09-12 05:41:23
【问题描述】:

当我在控件中从 xaml 设置集合值时,它似乎正确设置了值:

 <local:InjectCustomArray>
    <local:InjectCustomArray.MyProperty>
        <x:Array Type="local:ICustomType">
            <local:CustomType/>
            <local:CustomType/>
            <local:CustomType/>
        </x:Array>
    </local:InjectCustomArray.MyProperty>
 <local:InjectCustomArray>

如果值是从样式设置的,如果你在 ctor 中设置它的初始值,它似乎不会命中依赖属性回调:

   <local:InjectCustomArray>
        <local:InjectCustomArray.Style>
            <Style TargetType="local:InjectCustomArray">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding NonExistingProp}" Value="{x:Null}">
                        <Setter Property="MyProperty">
                            <Setter.Value>
                                <x:Array Type="local:ICustomType">
                                    <local:CustomType/>
                                    <local:CustomType/>
                                    <local:CustomType/>
                                    <local:CustomTypeTwo/>
                                </x:Array>
                            </Setter.Value>
                        </Setter>
                        <Setter Property="Background" Value="Black"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </local:InjectCustomArray.Style>
    </local:InjectCustomArray>

控制代码:

public partial class InjectCustomArray : UserControl
{
    public InjectCustomArray()
    {
        InitializeComponent();
        // If following line is being commented out then setter value in xaml is being set, otherwise not.
        MyProperty = new ICustomType[0];
    }

    public ICustomType[] MyProperty
    {
        get { return (ICustomType[])GetValue(MyPropertyProperty); }
        set { SetValue(MyPropertyProperty, value); }
    }

    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register("MyProperty", typeof(ICustomType[]), typeof(InjectCustomArray), new PropertyMetadata(Callback));

    private static void Callback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
      // This is being hit only once from a ctor.
      // If ctor is commented out then this value is being set from setter correctly.
    }
}

收藏品代码:

public interface ICustomType
{
}
public class CustomType : ICustomType
{
}    
public class CustomTypeTwo : ICustomType
{
}

问题:当 DependancyProperty 的值设置在接近的时间范围内时,是否有一些优化?这种行为的原因是什么?

【问题讨论】:

    标签: c# .net wpf xaml


    【解决方案1】:

    原因是本地属性值的优先级高于样式设置器中的值。

    您可以使用SetCurrentValue 方法来代替设置本地值:

    public InjectCustomArray()
    {
        InitializeComponent();
        SetCurrentValue(MyPropertyProperty, new ICustomType[0]);
    }
    

    有关详细信息,请参阅 MSDN 上的 Dependency Property Value Precedence 文章。

    【讨论】:

    • 好吧,一开始没说到点子上。因此,基本上实例中设置的值会覆盖样式中设置的值,其方式与您从 xaml 设置它们的方式相同。非常感谢!