【问题标题】:Can't override a global WPF style that is set by TargetType on a single specific control无法覆盖由 TargetType 在单个特定控件上设置的全局 WPF 样式
【发布时间】:2011-02-01 06:20:14
【问题描述】:

我的所有文本框都应用了一种样式,在资源字典中定义..

<Style TargetType="TextBlock">
        <Setter Property="TextBlock.FontSize" Value="{Binding Source={StaticResource ApplicationUserSettings}, Path=fontSize, Mode=OneWay}" />
        <Setter Property="TextBlock.TextWrapping" Value="Wrap" />
        <Setter Property="TextBlock.VerticalAlignment" Value="Center"/>
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="TextBox.FontFamily" Value="{Binding Source={StaticResource ApplicationUserSettings}, Path=fontName, Mode=OneWay}"/>
    </Style>\

fontsize 和 fontstyle 属性绑定到实现 iNotifyPropertyChanged 的​​特殊用户设置类,它允许对字体大小和 fontfamily 的更改立即在我的应用程序中传播。

但是,在我创建的 UserControl(具有讽刺意味的是,允许用户自定义其字体设置的屏幕)中,我希望字体大小和 fontfamily 保持不变。无论我尝试什么,我的全局字体设置都会覆盖我在用户控件中设置的内容:

<UserControl x:Class="ctlUserSettings"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:R2D2" Height="400" Width="600">

<Grid>

    <Grid.Resources>
        <Style x:Key="tbxStyle" TargetType="TextBox">
            <Style.Setters>
                <Setter Property="FontSize" Value="14"/>
                <Setter Property="FontFamily" Value="Tahoma"/>
            </Style.Setters>
        </Style>

...等等...

         <StackPanel Margin="139,122.943,41,0" Orientation="Horizontal" Height="33" VerticalAlignment="Top">
            <TextBox Style="{x:Null}" FontSize="13" FontFamily="Tahoma" HorizontalAlignment="Left" MaxWidth="500" MinWidth="350" Name="txtReaderPath" Height="Auto" VerticalAlignment="Top" />
            <TextBox Style="{x:tbxStyle}" Margin="15,0,0,0" HorizontalAlignment="Left" Name="txtPath" Width="43" Height="23" VerticalAlignment="Top">(some text)</Button>
        </StackPanel>

我尝试将 Style 设置为 {x:Null},设置内联自定义字体大小,并在此控件的资源中设置样式。没有一个优先于我的资源字典中的样式。

如您所见,我展示了我在上面的 XAML 示例中尝试过的所有内容...

我错过了什么?

【问题讨论】:

    标签: wpf user-controls styles font-size font-family


    【解决方案1】:

    另一种选择是在 UserControl 上添加一个空样式,例如:

    <UserControl.Resources>
            <Style TargetType="TextBlock" />
    </UserControl.Resources>
    

    这会阻止全局样式 - 也可以将其添加到 StackPanel 资源中以进行更细粒度的控制

    • 更长的解释here

    【讨论】:

      【解决方案2】:

      好的,我知道现在发生了什么。

      在我的 UserControl 的构造函数中,我什至尝试设置 .Style=Nothing,只是为了看看会发生什么......我的全局样式仍然出现并应用了自己。

      我必须假设在构造函数运行之后全局样式被应用到我的控件,因此无论如何全局样式都会侵入。最后,我只是将“全局”样式移动到一个只会影响我需要它的位置的位置。

      不太方便,但至少我可以继续我的项目

      【讨论】:

        猜你喜欢
        • 2019-06-26
        • 2012-01-18
        • 1970-01-01
        • 2021-12-23
        • 2017-04-02
        • 1970-01-01
        • 2011-01-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多