wpf - 如何根据目标设置 WPF 控件的样式?
问题描述
我有一个需要针对 .NET Framework 3.5 和 4.5 的项目,我想根据构建目标设置 WPF 控件的属性。例如。我有一个文本块,如果构建目标是 3.5,我希望它的背景是 Azure,如果构建目标是 4.5,我希望它的背景是青色我该怎么做?
<Window x:Class="WpfAppMultipleTarget.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfAppMultipleTarget"
mc:Ignorable="d"
Title="MainWindow" Height="300" Width="300">
<Grid>
<Grid.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Background" Value="Azure"/> <!-- If target is net framework 3.5 -->
<Setter Property="Background" Value="Cyan"/> <!-- If target is net framework 4.5 -->
</Style>
</Grid.Resources>
<TextBlock>Hello</TextBlock>
</Grid>
解决方案
可以使用 Interaction.Behaviors 来做到这一点,您可以在样式中包含的 XAML 中设置此属性。在行为内部,您可以阅读框架版本。这是一个例子。
<Style TargetType="{x:Type TextBox}">
<Style.Setters>
<Setter Property="i:Interaction.Behaviors">
<Setter.Value>
<local:BehaviorName/>
<local:BehaviorName/>
</Setter.Value>
</Setter>
</Style.Setters>
</Style>
您可以使用此代码来读取行为中的框架版本
string version = Assembly.GetExecutingAssembly().GetReferencedAssemblies().Where(c => c.Name.Contains("mscorlib")).FirstOrDefault().Version.ToString();
希望这可以帮助。
推荐阅读
- javascript - 在 Django 中动态查找模型对象并使用其数据更新页面
- quarkus - 如何使用 Mutiny 处理全部补偿?
- python - Pycharm 运行时:dir\that\doesnt\exist 中没有 Python
- python - mongo 聚合匹配 expr 不起作用,但 expr 似乎很好
- serialization - ONNX 序列化以字符串为输入的 Torch 模型
- php - notEqualTo in where cluase in zend
- sql - SQL Server - 根据条件从查询结果集中排除记录
- join - 如何组合来自多个算法输出的混淆矩阵?
- wordpress - Wordpress 类别循环无法检索 ACF 图像给出图像值:NULL
- pyspark - pySpark windows 分区 sortby 而不是 order by(感叹号)