[英]WPF C# Programmatically adding Styles from Resource Dictionary?
我是這個網站的新手,也是編程新手,我遇到了一個問題。 我正在使用 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”的資源字典,我不確定如何做到這一點。
是否有必要從代碼中更改它? 有很多方法作為觸發器或樣式選擇器
以下是可用於更改代碼內部樣式的代碼:
主窗口.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") });
}
}
}
讓我知道,如果它對你有用。
ResourceDictionary res = (ResourceDictionary)Application.LoadComponent(new Uri("TreeStyles.xaml", UriKind.Relative));
TestTree.Style = (Style)res["ProjectTree"];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.