gpt4 book ai didi

c# - 如何在运行时更改元素样式?

转载 作者:行者123 更新时间:2023-11-30 19:13:59 24 4
gpt4 key购买 nike

我有一个元素和多个样式,如何在运行时以编程方式或通过 XAML 绑定(bind)在样式之间切换。

<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 然后 Quality,我会同时获得边框和阴影。

最佳答案

这样的事情过去对我有用(纯 XAML 解决方案):

<!-- Styles 1-4 defined somewhere else on your page -->
<ComboBox Name="AvailableStyles">
<ComboBoxItem Tag="{x:Null}" IsSelected="True">None</ComboBoxItem>
<ComboBoxItem Tag="{StaticResource Style1}">1</ComboBoxItem>
<ComboBoxItem Tag="{StaticResource Style2}">2</ComboBoxItem>
<ComboBoxItem Tag="{StaticResource Style3}">3</ComboBoxItem>
<ComboBoxItem Tag="{StaticResource Style4}">4</ComboBoxItem>
</ComboBox>

<Button Content="Button" Style="{Binding ElementName=AvailableStyles, Path=SelectedItem.Tag}"/>
<CheckBox Content="Check Box" Style="{Binding ElementName=AvailableStyles, Path=SelectedItem.Tag}"/>
<RadioButton Content="Radio Button"Style="{Binding ElementName=AvailableStyles, Path=SelectedItem.Tag}"/>

希望这对您有所帮助!

关于c# - 如何在运行时更改元素样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1878046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com