2017-03-29 104 views
1

我有UserControl ImageView,我想添加一個名爲UseOverlay的cutom屬性。在初始化時未設置自定義依賴項屬性

<XAML> 

<UserControl x:Class="ImageView" .../> 

<XAML.cs> 
public partial class ImageView : UserControl 
{ 
    public static DependencyProperty UseOverlayProperty;  
    public ImageView() 
    { 
     InitializeComponent(); 
     if (UseOverlay) 
     { 
      AddOverlay(); 
     } 
    }  

    static ImageView() 
    { 
     UseOverlayProperty = DependencyProperty.Register("UseOverlay", typeof(bool), typeof(ImageView), new PropertyMetadata(false)); 
    } 

    public bool UseOverlay 
    { 
     get { return (bool)GetValue(UseOverlayProperty); } 
     set { SetValue(UseOverlayProperty, value); } 
    } 

} 

但是,從其他userControl使用時,未設置該屬性。將顯示ImageView,但沒有覆蓋,並且調試將UseOverlay顯示爲false。

<ImageView MaxWidth="450" UseOverlay="True"/> 

我錯過了什麼?

+0

你檢查你的輸出窗口任何錯誤消息? –

+0

你沒有錯誤或警告與此問題有關 – lewi

回答

2

目前UseOverlay僅在構造函數中使用過一次(根據默認值,它是false)。當應用UseOverlay="True"時,沒有任何反應。您需要添加DP ChangedCallback:

DependencyProperty.Register("UseOverlay", typeof(bool), typeof(ImageView), 
          new PropertyMetadata(false, UseOverlayChangedCallback)); 
​​
0

首先你不能在構造函數(內部消除默認值),使用它,並使用回調來更新佈局

#region --------------------Is playing-------------------- 
    /// <summary> 
    /// Playing status 
    /// </summary> 
    public static readonly DependencyProperty IsPlayingProperty = DependencyProperty.Register("IsPlaying", typeof(bool), typeof(WaitSpin), 
             new FrameworkPropertyMetadata(new PropertyChangedCallback(OnIsPlayingChanged))); 

    /// <summary> 
    /// OnIsPlayingChanged callback 
    /// </summary> 
    /// <param name="d"></param> 
    /// <param name="e"></param> 
    private static void OnIsPlayingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(d)) 
      return; 

     WaitSpin element = d as WaitSpin; 
     element.ChangePlayMode((bool)e.NewValue); 
    } 

    /// <summary> 
    /// IsPlaying 
    /// </summary> 
    [System.ComponentModel.Category("Loading Animation Properties"), System.ComponentModel.Description("Incates wheter is playing or not.")] 
    public bool IsPlaying 
    { 
     get { return (bool)GetValue(IsPlayingProperty); } 
     set { SetValue(IsPlayingProperty, value); } 
    } 
    #endregion 

你可以用這個添加默認,更換寄存器的最後一部分

new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, 
             RatingValueChanged) 
相關問題