1

你好,

所以这将是我的第一个问题,因为我没有找到任何可以回答我的问题的东西。


初始情况

SolidColorBrush在我的<Window.Resources>

<SolidColorBrush x:Key="BackgroundBrush" Color="{DynamicResource BackgroundColor}"/> 
<Color x:Key="BackgroundColor">PeachPuff</Color>

然后我把我的绑定BorderSolidColorBrush

<Border Background="{DynamicResource ResourceKey=BackgroundBrush}" />

在应用程序启动时,我读取了一个保存背景颜色的 xml 文件。

// Some XML Loading stuff -> backgroundColor is a Color
this.Resources["BackgroundColor"] = backgroundColor;

这就像一个魅力。我可以更改 xml 文件中的颜色,边框的背景是我在 xml 文件中定义的任何颜色。


实际问题

现在我将SolidColorBrush和的定义移到了Color我的App.xaml文件中,并将颜色更改为:

Application.Current.Resources["BackgroundColor"] = backgroundColor;

但是现在边界的背景不再改变了。它只是边框的默认颜色。无论我在我的 xml 文件中写什么。

当我调试里面的内容时

Application.Current.Resources["BackgroundColor"]

分配的颜色

Application.Current.Resources["BackgroundColor"] = backgroundColor;

实际上是在

Application.Current.Resources["BackgroundColor"]

但背景没有改变......


背景

我有两个窗户。一个主窗口和一个首选项窗口。在首选项窗口中,我希望能够更改主窗口的 F​​ontFamily/Type/Weight/Color 等。

我的第一种方法是在主窗口资源中定义所有样式并将我想要更改的值传递给首选项窗口并读出更改然后更新主窗口资源中的资源。

由于这非常有效,我现在想将样式移动到 app.xaml 并在那里读取和更新它们,这样我就不必将它们传递到首选项窗口并再次从那里读取它们。

4

2 回答 2

1

无法重现。以下代码适用于我(边框显示为天蓝色):

我的一个建议是确保您从窗口中删除了资源。XAML 绑定将绑定到最近的资源,即窗口资源(而不是应用程序资源),因此您将绑定到您未更改的资源。

MainWindow.xaml:

<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:wpfApplication3="clr-namespace:WpfApplication3"
        Title="MainWindow" Height="350" Width="525"
        x:Name="Window">
    <Window.Resources>
    </Window.Resources>

    <Grid>
        <Border Background="{DynamicResource BackgroundBrush}">
            <Button Margin="10">Test</Button>
        </Border>
    </Grid>

</Window>

应用程序.xaml:

<Application x:Class="WpfApplication3.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <SolidColorBrush x:Key="BackgroundBrush" Color="{DynamicResource BackgroundColor}"/>
        <Color x:Key="BackgroundColor">PeachPuff</Color>
    </Application.Resources>
</Application>

MainWindow.xaml.cs:

public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();
        Application.Current.Resources["BackgroundColor"] = Colors.Azure;
    }

}
于 2013-03-13T15:27:01.313 回答
0

好的,我找到了解决方案。

我将样式放入ResourceDictionary实际上没有任何帮助的样式中。

但:

当我在修改资源字典后重新加载它时,会应用样式。

实际上我认为它会在清除合并字典之前加载字典而不应用更改?

Application.Current.Resources["BackgroundColor"] = this.SelectedBackgroundColor;

Application.Current.Resources.MergedDictionaries.Clear();
var dictionary = new ResourceDictionary();
dictionary.Source = new Uri("ControlStyles.xaml", UriKind.Relative);
Application.Current.Resources.MergedDictionaries.Add(dictionary);
于 2013-03-14T08:14:57.433 回答