【问题标题】:WPF Set Static Resource At RuntimeWPF 在运行时设置静态资源
【发布时间】:2017-03-07 23:26:28
【问题描述】:

如何在运行时使用静态资源设置按钮的样式? 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>

App.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>

【问题讨论】:

  • StaticResource 不能在运行时更改,请改用 DynamicResource!
  • 澄清一下,我不想更改资源定义,只需将其应用于按钮

标签: c# wpf


【解决方案1】:

Background设置为静态资源的类比,但在运行时只是:

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

其中Resources 是带有目标画笔的ResourceDictionary,例如您的WindowUserControl 的根ResourceDictionary

【讨论】:

  • 如何访问我的App.xaml 文件中的资源字典?
  • @PatrickSchomburg 使用 System.Windows.Application.Current.Resources
猜你喜欢
  • 2022-12-04
  • 1970-01-01
  • 1970-01-01
  • 2010-10-25
  • 2011-12-10
  • 2013-10-23
  • 1970-01-01
  • 2015-01-22
  • 1970-01-01
相关资源
最近更新 更多