使用专用 XAML 文件交替 WPF 中元素的背景属性 [英] alternating BackGround property of an element in WPF using dedicated XAML File
问题描述
在 css 中,您可以从 html 文件中轻松调用任何样式通过代码改变给定元素中的一些样式属性
in css you can call from an html file any style and easily via code alter some property of style in a given element
所以在 C# WPF 中我想放置一个菜单按钮将允许改变背景
so in C# WPF i would like to place a menu button that will allow to alter the backGround
下面的 XAML 是 "Sample1" ,当前按原样硬编码,并在
范围内应用于当前 MainWindow.我如何创建 Sample2..4,5 以便通过 C#
代码,比如通过创建的样式"菜单按钮,我将能够更改元素的背景?
the XAML below is "Sample1" , is currently hardcoded as-is, and applied within a <Window.Background>
scope, to current MainWindow.
how can i create Sample2..4,5 so that via C#
code, say through the "Style" menu button created, i will be able to alter the BackGround of an element ?
在哪里可以有序地放置设置?
where could i place the settings in an orderly manner?
<LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5" x:Name="Sample1" Opacity="0.46">
<GradientStop Color="#8F63BADF" Offset="0.117" />
<GradientStop Color="#9D56B7C9" Offset="0.666" />
<GradientStop Color="#9343C0DB" Offset="0.279" />
<GradientStop Color="#E734ABDA" Offset="0.442" />
<GradientStop Color="#927FE2E2" Offset="0.802" />
<GradientStop Color="#E974CFC1" Offset="0.56" />
<GradientStop Color="#D076C5EB" Offset="0.255" />
</LinearGradientBrush>
推荐答案
您可以在 ResourceDictionary
中创建不同的样式,并在 App.xaml
中引用您的 ResourceDictionary.
You can create different styles in a ResourceDictionary
and reference your ResourceDictionary in your App.xaml
.
然后您可以随时从您的代码中更改任何元素的样式.
Then you can at any time from your code change the style of any element.
例如:
<ResourceDictionary>
<Style x:Key="Style1BackgroundRed" TargetType="{x:Type Window}">
<Setter Property="Background" Value="Red"/>
</Style>
<Style x:Key="Style2BackgroundGradient" TargetType="{x:Type Window}">
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5" x:Name="Sample1" Opacity="0.46">
<GradientStop Color="#8F63BADF" Offset="0.117" />
<GradientStop Color="#9D56B7C9" Offset="0.666" />
<GradientStop Color="#9343C0DB" Offset="0.279" />
<GradientStop Color="#E734ABDA" Offset="0.442" />
<GradientStop Color="#927FE2E2" Offset="0.802" />
<GradientStop Color="#E974CFC1" Offset="0.56" />
<GradientStop Color="#D076C5EB" Offset="0.255" />
</LinearGradientBrush>
</Setter.Value>
</Style>
</ResourceDictionary
在您的 App.xaml 中:
<Application.Resources>
<ResourceDictionary Source="/WhateverFolderYouUsedForYouStyles/StyleDictionary.xaml"/>
</Application.Resources>
来自您的窗口代码:
public MainWindow()
{
this.Style = (Style)Application.Current.FindResource("Style1BackgroundRed");
}
如果您想更改为另一种样式,同样可以找到另一种样式.
Same way you can find the other style if you want to change to that one.
这篇关于使用专用 XAML 文件交替 WPF 中元素的背景属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!