依赖属性优化?

时间:2016-09-12 05:41:23

标签: c# .net wpf xaml

当我在控件中设置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中是否有一些优化?这种行为的原因是什么?

1 个答案:

答案 0 :(得分:3)

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

您可以使用SetCurrentValue方法:

,而不是设置本地值
public InjectCustomArray()
{
    InitializeComponent();
    SetCurrentValue(MyPropertyProperty, new ICustomType[0]);
}

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