WPF 找不到资源

WPF can't find resource

我有一个关于WPF中查找资源的问题,我看了书上的查找资源机制

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.

我认为它就像泡泡路由事件。

所以我在堆栈面板中定义了一个资源,这里是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>

然后我尝试在按钮点击事件中更改动态资源,这里是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) };
    }
}

但是按钮的资源没有变化

请问这是什么原因造成的,怎么找资源。

您必须为按钮设置名称并在后面的代码中使用此名称

在xaml中:

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

在后面的代码中:

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

此代码适用于 DynamicResource。