2016-09-12 88 views
1

當我從XAML的控制之內。因而集收藏價值似乎正確地設定值:依賴屬性優化?

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

如果值被從風格設定,如果你設定的初始值也不會出現被擊中依賴屬性回調它在構造函數:

<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. 
    } 
} 

Collection項目編號:

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

問:是否有內DependancyProperty一些優化時,它的值被設定在接近的時間範圍內?這種行爲的原因是什麼?

回答

3

原因是本地屬性值的優先級高於樣式設置器的值。

而不是設置局部值,你可以使用SetCurrentValue方法:

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

請參見MSDN上Dependency Property Value Precedence文章的更多細節。

+0

好吧,一開始沒有點。因此,基本上在實例中設置的值將覆蓋按照從xaml設置它們的方式設置樣式的值。非常感謝! – Karolis