![](/img/trans.png)
[英]Change DefaultValue of DependencyProperty in Silverlight
[英]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 ); }
}
在我的聲明中, PropertyMetadata
的defaultValue
為null,我希望它是ThemeResource
的值。
可悲的是使用
<FontIcon x:Name="Glyph"
FontFamily="Segoe UI Symbol"
Glyph=""
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=""
FontSize="20"
Foreground="{Binding ForegroundColor,FallbackValue={StaticResource SystemControlHighlightAltChromeWhiteBrush}, ElementName=ColorCheckbox}" />
</UserControl>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.