在 WPF c 中更改代码的背景颜色#

Change Background Color from Code in WPF c#

提问人:user20202784 提问时间:11/10/2023 最后编辑:Clemensuser20202784 更新时间:11/10/2023 访问量:96

问:

我在我的 .xaml 代码中定义了背景:

<Window x:Class="BDE.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:BDE"
        mc:Ignorable="d"
        Title="BDE" Height="768" Width="1024"
        Background="#FF1B1534"
        FocusManager.FocusedElement="{Binding ElementName=txt_identifikationsnummer}"
        WindowState="Maximized" ResizeMode="CanResize" WindowStartupLocation="CenterScreen">

如何访问 .cs 代码中的背景属性以在函数中更改它

C# WPF XAML 颜色 背景

评论

0赞 GinCanhViet 11/10/2023
控制。背景 = (SolidColorBrush)new BrushConverter()。转换FromString(“#082049”);
0赞 user20202784 11/10/2023
我无法控制。背景。刚刚获取 Control.BackgroundProperty

答:

0赞 MIHOW 11/10/2023 #1

如果通过 .cs 代码,您的意思是 后面的代码,那么您可以更改颜色,例如在 的构造函数中,如下所示WindowBackgroundMainWindow

public MainWindow()
{
    InitializeComponent();
    Background = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
}

或者在 MainWindow 类的任何其他方法中。

评论

0赞 Clemens 11/10/2023
为什么你认为你不能在构造函数之外使用?this
0赞 MIHOW 11/10/2023
没错,没有必要通过对象的名称来引用,只要是我们想要引用的对象即可。this
0赞 Clemens 11/10/2023
您写道,可以在构造函数中更改该属性。这是误导性的。可以在 MainWindow 类的任何方法中更改该属性。