Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 701
Darren A. Avatar asked Jan 18 '26 02:01

Darren A.


2 Answers

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.

like image 101
Miroslav Endyš Avatar answered Jan 19 '26 17:01

Miroslav Endyš


ResourceDictionary res = (ResourceDictionary)Application.LoadComponent(new Uri("TreeStyles.xaml", UriKind.Relative));
TestTree.Style = (Style)res["ProjectTree"];

Load Style From Resource File And Set To Elements programmatically

like image 40
Shahin Mohammadi Avatar answered Jan 19 '26 18:01

Shahin Mohammadi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!