簡體   English   中英

UWP:使用DefaultValue ThemeResource的DependencyProperty

[英]UWP: DependencyProperty with DefaultValue ThemeResource

我有一個自定義的UIElement,其中FontIcon作為正文。

這個FontIcon有一個Foreground屬性,我想綁定到DependencyProperty

DependencyProperty聲明如下:

public static readonly DependencyProperty ForegroundColorProperty = DependencyProperty.Register( "ForegroundColor", typeof( Brush ),
                                                                  typeof( ColorableCheckbox ),
                                                                  new PropertyMetadata( null, null ) );

public Brush ForegroundColor
  {
     get { return (Brush)GetValue( ForegroundColorProperty ); }
     set { SetValue( ForegroundColorProperty, value ); }
  }

在我的聲明中, PropertyMetadatadefaultValue為null,我希望它是ThemeResource的值。

可悲的是使用

<FontIcon x:Name="Glyph"
          FontFamily="Segoe UI Symbol"
          Glyph="&#xE001;"
          FontSize="20"
          Foreground="{Binding Path=ForegroundColor,FallbackValue={ThemeResource SystemControlHighlightAltChromeWhiteBrush}}" />

不起作用,它給出一個錯誤:

{DynamicResource} can only be used with dependency property

如何設置ThemeResource的默認值? 在使用PropertyMetadata代碼隱藏中還是在XAML中?

如果調用方法在PropertyMetadata中的屬性更改回調中設置“Glyph”的前景,該怎么辦?

所以像這樣......

public static readonly DependencyProperty ForegroundColorProperty = DependencyProperty.Register("ForegroundColor", typeof(Brush), typeof(ColorableCheckbox), new PropertyMetadata(null, UpdateForeground));

private static void UpdateForeground(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
    var ctrl = (ColorableCheckbox) obj;
    var brush = args.NewValue as Brush;

    if (brush == null)
        return;

    ctrl.Glyph.Foreground = brush;
}

或者在XAML中為您的用戶控制一個名稱並將其設置為綁定的源。

例如

<UserControl x:Name="ColorCheckbox"...>
   <FontIcon x:Name="Glyph"
          FontFamily="Segoe UI Symbol"
          Glyph="&#xE001;"
          FontSize="20"
          Foreground="{Binding ForegroundColor,FallbackValue={StaticResource SystemControlHighlightAltChromeWhiteBrush}, ElementName=ColorCheckbox}" />
</UserControl>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM