初始化时未设置自定义依赖项属性

时间:2017-03-29 11:30:17

标签: wpf dependency-properties

我有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"/>

我错过了什么?

2 个答案:

答案 0 :(得分:2)

目前UseOverlay在构造函数中只使用一次(根据默认值为false)。当UseOverlay="True"应用时,没有任何反应。您需要添加DP ChangedCallback:

DependencyProperty.Register("UseOverlay", typeof(bool), typeof(ImageView),
                            new PropertyMetadata(false, UseOverlayChangedCallback));
private static void UseOverlayChangedCallback(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
    if ((bool) e.NewValue)            
        ((ImageView)obj).AddOverlay();
    else
        ((ImageView)obj).HideOverlay();
}

答案 1 :(得分: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)