簡體   English   中英

WPF找不到資源

[英]WPF can't find resource

我有一個關於在WPF中查找資源的問題,並且閱讀了從書本中查找資源的機制。

它說UIElement將首先找到其資源屬性,如果不合適,則將找到其父級的資源屬性,依此類推,直到應用程序資源屬性為止。

我認為這就像泡沫事件一樣。

所以我在stackpanel中定義了一個資源,這里是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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM