Search code examples
c#wpfstylesresourcedictionaryinlines

WPF C# Programmatically adding Styles from Resource Dictionary?


I am new to this website and new to programming and I have encountered a problem. I am using Visual Studio 2010, C# WPF Application.

I have this line of code in my program:

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

This Line doesn't have any problems, but I have a Resource Dictionary already made with those setters and I'm not sure how I can use it programmatically for each line. I tried something like this but it didn't do anything:

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

What I think the problem might be is that I'm not calling the Resource dictionary which is called "Styles.xaml" in the code and I am unsure on how to do that.


Solution

  • Is it necessary to change it from code? There are lot of approaches as Triggers or StyleSelectors

    Here is the code you can use for changing style inside of code:

    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") });
        }
    }
    }
    

    Let me know, if it si usable for you.