开发者

Applying a FontFamily to all Controls in Silverlight 4 Beta

开发者 https://www.devze.com 2022-12-12 02:20 出处:网络
I\'d like to give every Control a certain FontFamily and FontWeight in Silverlight 4.0. I know that styles can now apply to all controls of a certain type, so I tried this:

I'd like to give every Control a certain FontFamily and FontWeight in Silverlight 4.0. I know that styles can now apply to all controls of a certain type, so I tried this:

<Style TargetType="Control">
    <Setter Property="FontFamily" Value="Arial" />
    <Setter Property="FontWeight" Value="Bold" />
</Style>

Unfortunately, that doesn't appear to work. I can do this for types that derive from Control, however. For example, setting TargetType to Button applies those values to 开发者_JAVA百科every Button in my application.

Why can't I do this for the Control base class, then?


The control styling being tied to the type system can be a bit misleading. Its actually based on the value of the controls DefaultStyleKey property. In the case of a Button the value is typeof(Button) and for a TextBox it is typeof(Textbox).

A default style will be applied to a control if the TargetType value equals the controls DefaultStyleKey value. There is no examination of whether the Type in the DefaultStyleKey is a derivative of the TargetType.

Font related properties are a special case since most controls will inherit the values for Font properties from the containing context. Hence you can effectively acheive the same result by specifying FontFamily and FontWeight on the UserControl element.

Edit

From a comment by the OP:-

I was hoping that I could set it in one place and have every UserControl in the entire application take on that style.

The closest you can get to that is to place a keyed style in the app resources and ensure all the usercontrols bind to that style. Of course this still requires some co-operation for each user control but at least the font choices remain in a single place.

For example in app.xaml:-

<Style x:Key="Common" TargetType="UserControl">
    <Setter Property="FontFamily" Value="Arial" />
    <Setter Property="FontWeight" Value="Bold" />
<Setter Property="Foreground" Value="Blue" />

Then in each usercontrol:-

<UserControl ...namespace stuff here...
   Style="{StaticResource Common}">
  <!-- ... content here ... -->


I do it by specifying FontFamily in my root visual. All child controls without explicit FontFamily set, derive FontFamily from the root visual.

Only ChildWindow needs extra FontFamily setting, because it is hosted in "über" root visual (as popup).


This would be of help:

this.RootVisual = New MainPage();
(MainPage)this.RootVisual.FontFamily 
  = New System.Windows.Media.FontFamily(
    "/SLApplication;component/Fonts/segoeui.ttf#Segoe UI");
0

精彩评论

暂无评论...
验证码 换一张
取 消