想要使用XAML RESOURCE FILE改变窗口颜色

本文关键字:FILE 改变 窗口 颜色 RESOURCE XAML | 更新日期: 2023-09-27 18:10:16

我想通过应用在XAML RESOURCE FILE中定义的样式来改变窗口的颜色。我已经创建了一个样式,目标类型设置为window,没有键(假设它将自动应用于所有窗口)。但是样式并没有应用到我的应用程序的窗口。使用下面的代码只适用于窗口中的控件,但它不会改变窗口本身的颜色。请让我知道我错在哪里。如果我给目标类型grid,它会改变颜色,但如果我给window,它不会改变颜色

资源文件

<Color x:Key="MainBackgroundColor"></Color>
<SolidColorBrush x:Key="MainBackground" 
                    Color="{Binding Path=DataContext.MainApplicationColor,
    UpdateSourceTrigger=PropertyChanged,
    RelativeSource={RelativeSource AncestorType={x:Type Window}, Mode=FindAncestor}, 
    FallbackValue={StaticResource MainBackgroundColor}}"/>

<Style TargetType="Window">
    <Setter Property="Background" Value="{StaticResource MainBackground}" />            
</Style>

视图

<Window x:Class="MvvmLight1.View.MainMenuView"
        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:ignore="http://www.ignore.com"
        mc:Ignorable="d ignore"  Name="x_main" 
        >
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/ColorResources.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <Grid Height="60" Width="60">
    </Grid>
</Window>

视图模型*

public string ChangeColorCommandText { get; set; }
private RelayCommand m_cmdChangeColor;
public ICommand ChangeColor
{
    get { return m_cmdChangeColor ?? (m_cmdChangeColor = new RelayCommand(ChangeColorAction, () => true)); }
}

private void ChangeColorAction()
{
    MainApplicationColor = (Color)ColorConverter.ConvertFromString("#4484F3");
}

想要使用XAML RESOURCE FILE改变窗口颜色

Target类型不应用于您的窗口的原因是因为,这里您使用的是名称为"MainMenuView"的窗口的派生类型。 Styles中的TargetType不管理派生类型。所以在样式资源中,你必须将目标类型设置为派生类型(MainMenuView)。通过这样做,它将只应用于MainMenuView窗口。

xmlns:local="Yournamespace:YourApplication"
<Style  TargetType="local:MainMenuView">
     <Setter Property="Background" Value="Green" />
</Style>

要将样式应用到应用程序中的所有窗口,那么有必要为定义的样式设置x:键,并在xaml或后面的代码中引用所有窗口的样式。