WPF无法找到资源

时间:2017-04-16 03:07:41

标签: c# wpf xaml resourcedictionary

我有一个关于在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) };
    }
}

但是按钮的资源并没有改变。

那么是什么导致这种情况发生,以及如何能够发现资源。

1 个答案:

答案 0 :(得分:0)

您必须为按钮设置名称,并在

后面的代码中使用此名称 xaml中的

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

loop

此代码适用于DynamicResource。

相关问题