我有这样的风格:
<Style TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
...
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
默认情况下,它将应用于所有操作系统中的所有按钮,但我只想在用户使用Windows 8时应用它。
检查Environment.OSVersion.Version
属性后,有没有办法从代码隐藏中激活样式?或者有更好的方法吗?
答案 0 :(得分:1)
我认为风格是基于主题的,不能基于操作系统版本。
答案 1 :(得分:1)
找到你的引导程序代码(在显示XAML之前执行的代码)并创建一个简单的开关,它将根据操作系统版本选择正确的XAML文件。
Uri uri = new Uri("/OS7.xaml", UriKind.Relative);
StreamResourceInfo info = Application.GetResourceStream(uri);
XamlReader reader = new System.Windows.Markup.XamlReader();
var dic = (ResourceDictionary)reader.LoadAsync(info.Stream);
//then locate ResourceDictionary throgh Application.Current.Resources
yourDictionary.MergedDictionaries.Add(dic);
您还可以创建绑定到静态OS版本属性的简单触发器并切换Button的模板,但这是相当有限的,因为您只能交换模板。它可能对你有帮助;
<Window.Resources>
<ControlTemplate x:Key="OS7" TargetType="Button">
<Border x:Name="Border" CornerRadius="2" BorderThickness="1" Background="blue" BorderBrush="blue">
<ContentPresenter Margin="2" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</ControlTemplate>
<!-- DEFALT -->
<Style TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="Border" CornerRadius="2" BorderThickness="1" Background="red" BorderBrush="blue">
<ContentPresenter Margin="2" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<!-- Just an example. Replace IsMouseOver with DataTrigger and STATIC binding against OS version-->
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Template" Value="{StaticResource OS7}" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>