Windows Phone 8为依赖项属性设置默认属性

时间:2014-03-25 12:45:42

标签: c# wpf xaml windows-phone-8 dependency-properties

我正在为我的WP8应用程序创建一个控件。我试图为依赖属性设置值,而不管其默认值。以下是我的代码

public BitmapImage EnabledImage { get; set; }
    public BitmapImage DisabledImage { get; set; }

    public bool ControlEnabled
    {
        get { return (bool)GetValue(ControlEnabledProperty); }
        set { SetValue(ControlEnabledProperty, value); }
    }

    public static readonly DependencyProperty ControlEnabledProperty =
        DependencyProperty.Register("ControlEnabled", typeof(bool), typeof(ucControl), new PropertyMetadata(OnImageStatePropertyChanged));

    private static void OnImageStatePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var control = (d as ucControl);
        control.ControlEnabled = Convert.ToBoolean(e.NewValue);
        control.OnImageStateChanged(e.NewValue);
    }

    private void OnImageStateChanged(object newValue)
    {
        if (Convert.ToBoolean(newValue) == true)
            imgControl.Source = EnabledImage;
        else
            imgControl.Source = DisabledImage;
    }

这是我如何在xaml中调用它

<WP8:ucControl Grid.Row="0" Grid.Column="0" Height="92" Width="92" EnabledImage="/Images/img_on.png" DisabledImage="/Images/img_off.png" ControlEnabled="True"/>

设置 ControlEnabled =“False”时,它不会设置值。意味着禁用图像未在图像控制上设置。

我希望此控件设置属性,而不管其默认值。

我也推荐这篇文章但解决方案不起作用:Windows Phone 8, use DependencyProperty for a usercontrol, PropertyChangedCallback and CoerceValueCallback issue

任何想法在这里有什么不妥。

1 个答案:

答案 0 :(得分:0)

您可以将代码修改为此,然后尝试:

public static readonly DependencyProperty ControlEnabledProperty =
    DependencyProperty.Register("ControlEnabled", typeof(bool?), typeof(ucControl), new PropertyMetadata(null, OnImageStatePropertyChanged));