WPF C#以编程方式从资源字典添加样式?
我是这个网站的新手,也是编程新手,我遇到了一个问题。 我正在使用VisualStudio2010,C#WPF应用程序 我的程序中有以下代码行:WPF C#以编程方式从资源字典添加样式?,c#,wpf,styles,resourcedictionary,inlines,C#,Wpf,Styles,Resourcedictionary,Inlines,我是这个网站的新手,也是编程新手,我遇到了一个问题。 我正在使用VisualStudio2010,C#WPF应用程序 我的程序中有以下代码行: TextBlock.Inlines.Add (new Run("text"){ Foreground = Brushes.Blue, FontWeight = FontWeights.ExtraBold }); 这一行没有任何问题,但我已经用这些setter创建了一个资源字典,我不确定如何以编程方式为每一行使
TextBlock.Inlines.Add
(new Run("text"){ Foreground = Brushes.Blue, FontWeight = FontWeights.ExtraBold });
这一行没有任何问题,但我已经用这些setter创建了一个资源字典,我不确定如何以编程方式为每一行使用它。我尝试过这样的方法,但没有任何效果:
TextBlock.Inlines.Add
(new Run("text") { Style = (Style)this.Resources["bluebold"] });
我认为可能的问题是,我没有调用代码中名为“Styles.xaml”的资源字典,我不确定如何执行该操作。是否需要从代码中更改它?有很多方法可以作为触发器或样式选择器 以下是可用于更改代码内部样式的代码: MainWindow.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>
MainWindow.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") });
}
}
}
使用System.Windows;
名称空间样式FromResourceExample
{
///
///MainWindow.xaml的交互逻辑
///
公共部分类主窗口:窗口
{
公共主窗口()
{
初始化组件();
}
私有无效按钮\u单击(对象发送者,路由目标e)
{
Add(新运行(“新文本”){Style=(Style)this.FindResource(“RunStyle1”)});
}
}
}
如果它对您有用,请告诉我。我有多个按钮,可以将不同颜色的文本添加到文本块中,这就是为什么我需要它的原因。据我所知,您提供的代码将文本块中的所有样式更改为一种样式。我尝试使用TextBlock.Inlines.Add(newrun(“text”){Style=(Style)this.FindResource(“stylename”)});但它给了我一个错误:“TextBlock”TargetType与元素“Run”的类型不匹配。好的,我更改了资源的样式和名称。。。试试这个是的让TargetType运行使它工作!非常感谢D