2014-03-25 177 views
0

我爲WP8應用程序創建了一個控件。我試圖爲依賴項屬性設置值,而不管它的默認值如何。下面是我的代碼Windows Phone 8爲依賴項屬性設置了默認屬性

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 =「假」調用它。意味着禁用圖像未在圖像控制上設置。

我希望此控件設置屬性,而不考慮它的默認值。

我指這篇文章很好,但解決方案不工作:Windows Phone 8, use DependencyProperty for a usercontrol, PropertyChangedCallback and CoerceValueCallback issue

任何想法有什麼錯在這裏。

回答

0

你可以修改你的代碼這一點,並嘗試:

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