首页 > 解决方案 > WPF:通过 ComboBox 选择上的 DataTrigger 更改样式 FontSize

问题描述

我是 XAML 和 WPF 的新手。我的目的是通过 ComboBox 更改出现在我的窗口中的所有“文本”控件的所有 FontSize。

组合框字体大小

我在窗口中声明了我的风格:

       <Style x:Name="ControlBaseStyle" x:Key="ControlBaseStyle" TargetType ="{x:Type Control}">
           <Setter Property="FontSize" Value="11"/>
           <Setter Property="Background" Value="Transparent"/>
           <Setter Property="BorderBrush" Value="Transparent"/>
           <Setter Property="BorderThickness" Value="1"/>
       </Style>
       .
       .
       .
   </Window.Resources>

我想将第一个 setter 链接到我的 ComboBox:

               <ComboBox Name="CBFontSize" Style="{StaticResource ControlBaseStyle}" SelectedIndex="3" HorizontalAlignment="Stretch" VerticalAlignment="Center" SelectionChanged="CBFontSize_SelectionChanged">
                   <ComboBoxItem>8</ComboBoxItem>
                   <ComboBoxItem>9</ComboBoxItem>
                   <ComboBoxItem>10</ComboBoxItem>
                   <ComboBoxItem>11</ComboBoxItem>
                   <ComboBoxItem>12</ComboBoxItem>
                   <ComboBoxItem>14</ComboBoxItem>
                   <ComboBoxItem>16</ComboBoxItem>
                   <ComboBoxItem>18</ComboBoxItem>
                   <ComboBoxItem>20</ComboBoxItem>
                   <ComboBoxItem>22</ComboBoxItem>
                   <ComboBoxItem>24</ComboBoxItem>
               </ComboBox>

我尝试通过绑定设置 FontSize-Setter 的值,但它不起作用:

        <Setter Property="FontSize" Value="{Binding SelectedItem, ElementName=CBFontSize}"/>

我尝试通过 DynamicResource 设置它(并使用 CBFontSize_SelectionChanged 修改值),但没有任何反应:

       <Style x:Name="ControlBaseStyle" x:Key="ControlBaseStyle" TargetType ="{x:Type Control}">
           <Setter Property="FontSize" Value="{DynamicResource ResourceKey=MyFontSize}"/>
       </Style>


       private void CBFontSize_SelectionChanged(object sender, SelectionChangedEventArgs e)
       {
           if (double.TryParse(CBFontSize.SelectedItem?.ToString() ?? "", out double mfs))
           {
               Resources["MyFontSize"] = mfs;
           }
       }

我尝试通过 DataTrigger 设置它,但我不知道如何传递值:

        <Style.Triggers>
            <DataTrigger x:Name="MyDataTrigger" Binding="{Binding SelectedItem, ElementName=CBFontSize}">
                <Setter Property="FontSize" Value="{Binding Value, ElementName=MyDataTrigger}"/>
            </DataTrigger>
        </Style.Triggers>

有人能帮我吗?

PS我不假装解决方案必须遵循我的代码/方法,任何方法对我来说都可以。我只是想象有一个相对简单的解决方案,我太愚蠢/无知,看不到

标签: wpfxamlcomboboxstylesfont-size

解决方案


我找到了一个简单的解决方案。我将它发布给可能最终处于相同情况的任何人:

    <Style x:Name="ControlBaseStyle" x:Key="ControlBaseStyle" TargetType ="{x:Type Control}">
        <Setter Property="FontSize" Value="{Binding ElementName=CBFontSize, Path=SelectedValue.Content}"/>
        .
        .
        .
    </Style>

我的错误是我绑定了 ComboBox 的 SelectedValue,在我过去使用 WindowsForm 的经验中包含有效值,但在 WPF 中,ComboBox 的 SelectedValue 是 ComboBoxItem,因此我必须获取该项目的内容。现在它可以工作了:)


推荐阅读