wpf - 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我不假装解决方案必须遵循我的代码/方法,任何方法对我来说都可以。我只是想象有一个相对简单的解决方案,我太愚蠢/无知,看不到
解决方案
我找到了一个简单的解决方案。我将它发布给可能最终处于相同情况的任何人:
<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,因此我必须获取该项目的内容。现在它可以工作了:)
推荐阅读
- azure-ad-b2c - azure ad b2c 自定义策略中验证技术配置文件的前提条件评估不起作用
- android - 从 onClickListerner 访问现有的 json 对象
- angular - 交换 Nebular 主题时更改 Bootstrap 表格字体颜色
- powerapps - 将 2 个共享点列表的数据加载到电源应用程序中的单个库的任何功能?
- go - 使用等待组来完成 goroutine
- c# - 为什么操作符的行为类似于 == 操作符?
- c - 自定义读线功能
- visual-studio-code - 如何在 VS Code 中为单个变量启用类型注释
- javascript - 如何解决 onmouseover 事件中的过渡问题?
- android - iOS idfa 和 android 广告 id 是否彼此唯一?