gpt4 book ai didi

c# - WPF 在运行时设置静态资源

转载 作者:行者123 更新时间:2023-11-30 23:15:21 25 4
gpt4 key购买 nike

如何使用静态资源在运行时设置按钮的样式? xaml 看起来像这样:

<Button  Grid.Column="0" Grid.Row="2"  VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Margin="1,0,1,0" 
Background="{StaticResource OrangeGradient}" FontFamily="Lucida Sans" BorderBrush="Black" >

Background="{StaticResource OrangeGradient}" 在运行时在 c# 中会是什么样子?

我的资源字典,Resources/Styles.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:myProj">

<LinearGradientBrush x:Key="OrangeGradient" EndPoint="0.5,1" StartPoint="0.5,0">
<LinearGradientBrush.RelativeTransform>
<TransformGroup>
<ScaleTransform CenterY="0.5" CenterX="0.5"/>
<SkewTransform CenterY="0.5" CenterX="0.5"/>
<RotateTransform Angle="270" CenterY="0.5" CenterX="0.5"/>
<TranslateTransform/>
</TransformGroup>
</LinearGradientBrush.RelativeTransform>
<GradientStop Color="#FFE08A19" Offset="0"/>
<GradientStop Color="#FFF5CA86" Offset="1"/>
</LinearGradientBrush>

应用程序.xaml:

<Application x:Class="myProj.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:myProj"
StartupUri="MainWindow.xaml">

<Application.Resources>

<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

</Application.Resources>

</Application>

最佳答案

模拟将 Background 设置为静态资源,但在运行时只是:

yourButton.Background = (Brush)this.Resources["OrangeGradient"];

其中 Resources 是带有目标刷的 ResourceDictionary,例如 Window 的根 ResourceDictionary用户控件

关于c# - WPF 在运行时设置静态资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42651480/

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