maoleigepu
maoleigepu

Reputation: 153

WPF can't find resource

I have a question about finding resources in WPF, and I read the mechanism of finding resources from book.

It said that a UIElement will find its resources attribute first, if nothing fit then it will find its parent's resources attribute and so on, till application resources attribute.

I think it just like bubble routed event.

So I define a resource in stackpanel, here is the xaml.

<Window x:Class="DynamicResource.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:DynamicResource"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<StackPanel x:Name="stackPanel">
    <StackPanel.Resources>
        <TextBlock x:Key="res1" Text="this is staticresource" Background="Beige"></TextBlock>
        <TextBlock x:Key="res2" Text="this is dynamicresource" Background="DarkGoldenrod"></TextBlock>
    </StackPanel.Resources>

    <Button Margin="5,5,5,0" Content="{StaticResource res1}"></Button>
    <Button Margin="5,5,5,0" Content="{DynamicResource res2}"></Button>
    <Button x:Name="button" Margin="5,5,5,0" Content="refresh resource" Click="Button_Click"></Button>
</StackPanel>

Then I try to change dynamic resource in the button click event, here is xaml.cs

 public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        //Can find target resource
        //stackPanel.Resources["res1"] = new TextBlock() { Text = "this is new staticresource", Background = new SolidColorBrush(Colors.Tan) };
        //stackPanel.Resources["res2"] = new TextBlock() { Text = "this it new dynamicresouce", Background = new SolidColorBrush(Colors.Magenta) };

        //Can't find target resource
        button.Resources["res1"] = new TextBlock() { Text = "this is new staticresource", Background = new SolidColorBrush(Colors.Tan) };
        button.Resources["res2"] = new TextBlock() { Text = "this it new dynamicresouce", Background = new SolidColorBrush(Colors.Magenta) };
    }
}

But the resource of button didn't change.

So what cause this happened, and how could to bubbly find resources.

Upvotes: 1

Views: 3275

Answers (1)

mehdi farhadi
mehdi farhadi

Reputation: 1532

you must set name for button and use this name in code behind

in xaml:

<Button Margin="5,5,5,0" Name="btnRes2" Content="{DynamicResource res2}"></Button>

in code behind :

private void Button_Click(object sender, RoutedEventArgs e)
{
    btnRes2.Resources["res2"] = new TextBlock() { Text = "this it new dynamicresouce", Background = new SolidColorBrush(Colors.Magenta) };
}

this code work for DynamicResource.

Upvotes: 4

Related Questions