UWP:具有默认值 ThemeResource 的 DependencyProperty

UWP: DependencyProperty with DefaultValue ThemeResource

我有一个以 FontIcon 作为正文的自定义 UIElement。

这个 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 为空,我希望这是 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 的 属性 changed 回调中调用一个方法来设置 "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>