1

我是这个网站的新手,也是编程新手,我遇到了一个问题。我正在使用 Visual Studio 2010,C# WPF 应用程序。

我的程序中有这行代码:

    TextBlock.Inlines.Add
                  (new Run("text"){ Foreground = Brushes.Blue, FontWeight = FontWeights.ExtraBold });

这条线没有任何问题,但我已经用这些设置器制作了一个资源字典,我不确定如何以编程方式为每一行使用它。我尝试了这样的事情,但它没有做任何事情:

TextBlock.Inlines.Add
             (new Run("text") { Style = (Style)this.Resources["bluebold"] });

我认为问题可能是我没有调用代码中称为“Styles.xaml”的资源字典,我不确定如何做到这一点。

4

1 回答 1

1

是否有必要从代码中更改它?有很多方法作为触发器或样式选择器

以下是可用于更改代码内部样式的代码:

主窗口.xaml

<Window x:Class="StylesFromResourceExample.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <Style x:Key="RunStyle1" TargetType="{x:Type Run}">
        <Setter Property="Foreground" Value="Blue"/>
        <Setter Property="FontWeight" Value="ExtraBold"/>
    </Style>    </Window.Resources>
<Grid>
    <TextBlock x:Name="txtBlock" HorizontalAlignment="Left" Text="TextBlock" VerticalAlignment="Top" Height="20" Width="142" />
    <Button Width="100" Height="30" Content="Change" Click="Button_Click" />
</Grid>
</Window>

主窗口.xaml.cs

using System.Windows;

namespace StylesFromResourceExample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        txtBlock.Inlines.Add(new Run("New Text") { Style = (Style)this.FindResource("RunStyle1") });
    }
}
}

让我知道,如果它对你有用。

于 2014-12-06T14:22:53.413 回答