WPF click button to change content

In WPF, there are two running states for the use of resources, namely static and dynamic. Static resource refers to the one-time use of resources when loading memory in a program, and then it will not be accessed again. Dynamic resource refers to the use of resources while running a program. Then I will visit this resource again.
Of course, we usually use static resources, but if we call for special operations, such as clicking the button to change the content, we need to use our dynamic resource, because dynamic resources will continue to access this resource during the process of program running.

Here is an example:

<Window x:Class="WpfApplication1.Window1"
        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:WpfApplication1"
        mc:Ignorable="d"
        Title="Window1" Height="300" Width="300" FontSize="20">
    <Window.Resources>
        <TextBlock x:Key="str1" Text="Test one"></TextBlock>
        <TextBlock x:Key="str2" Text="Test two"></TextBlock>
    </Window.Resources>
    <StackPanel>
        <Button Margin="5" Content="{StaticResource str1}"></Button>
        <Button Margin="5" Content="{DynamicResource str2}"></Button>
        <Button Margin="5" Content="modify" Click="Button_Click"></Button>
    </StackPanel>
</Window>

The simple resources of the front-end code need to change the static resources to dynamic resources. The third button on the page is responsible for clicking the button to change the two resources during the program running.

Here is the button background code

private void Button_Click(object sender, RoutedEventArgs e)
 {
        this.Resources["str1"] = new TextBlock() { Text = "Hello, the world" };
        this.Resources["str2"] = new TextBlock() { Text = "Hello world" };
 }

Before clicking:

After clicking:

Because the first button uses resources in a static way, clicking modify will not change the content.

Posted by sparks on Tue, 22 Oct 2019 11:07:09 -0700