2017-03-29 77 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) 
相关问题