【发布时间】:2009-12-10 01:09:27
【问题描述】:
我有一个元素和多个样式,如何在运行时以编程方式或通过 XAML 绑定在样式之间切换。
<Rectangle x:Name="fixtureControl" Style="{DynamicResource FixtureStyle_Fast}">
<!-- In the style resources. -->
<Style x:Key="FixtureStyle_Fast" TargetType="{x:Type Shape}">
<Setter Property="Stroke" Value="Black"/>
<Setter Property="StrokeThickness" Value="20"/>
</Style>
<Style x:Key="FixtureStyle_Good" TargetType="{x:Type Shape}">
<Setter Property="Effect">
<Setter.Value>
<DropShadowEffect Opacity=".9"
Direction="-90"
RenderingBias="Performance"
BlurRadius="50"
ShadowDepth="10" />
</Setter.Value>
</Setter>
</Style>
<Style x:Key="FixtureStyle_Best" TargetType="{x:Type Shape}">
<Setter Property="Effect">
<Setter.Value>
<DropShadowEffect Opacity=".9"
Direction="-90"
RenderingBias="Quality"
BlurRadius="50"
ShadowDepth="10" />
</Setter.Value>
</Setter>
</Style>
然后我有一些处理更改样式的单选按钮
private void RadioButton_Click(object sender, RoutedEventArgs e) {
if (e.Source == rdoQualityBest) {
fixtureControl.Style = FindResource("FixtureStyle_Best") as Style;
} else if (e.Source == rdoQualityGood) {
fixtureControl.Style = FindResource("FixtureStyle_Good") as Style;
} else {
fixtureControl.Style = FindResource("FixtureStyle_Fast") as Style;
}
}
但是,这会将样式应用于元素,而不是替换它,所以如果我应用 Fast then Quality,我会同时获得边框和阴影。
【问题讨论】:
-
我无法真正为您提供答案,但我相信如果您想通过 XAML 绑定处理样式,您应该查看触发器。这是一篇可能有用的 CodeProject 文章:codeproject.com/KB/WPF/codeVsXAML.aspx