依赖属性优化

本文关键字:优化 属性 依赖 | 更新日期: 2023-09-27 18:06:46

当我在控件内设置来自xaml的集合值时,它似乎正确地设置了值:

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

如果value是从样式中设置的,那么如果你在actor中设置了它的初始值,那么它似乎不会击中依赖属性回调:

   <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当它的值被设置在接近的时间范围内?这种行为的原因是什么?

依赖属性优化

原因是本地属性值比Style Setter的值具有更高的优先级。

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

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

请参阅MSDN上的依赖属性值优先级文章了解更多详细信息。