【问题标题】:Custom Color from xaml equivalent in C# code-behind来自 C# 代码隐藏中的 xaml 等效项的自定义颜色
【发布时间】:2019-07-20 17:16:43
【问题描述】:

我在一个有网格的 wpf 应用程序中有一个窗口。 网格有一个十六进制的背景值。 我只想从后面的代码中检查该背景的值是否是我真正的意思。

<Grid Background="#424242" Name="GridMain">

在我得到的代码中:

SolidColorBrush a = new SolidColorBrush();
var b = (SolidColorBrush)new BrushConverter().ConvertFrom("#424242");
MainWindow mainWin = Application.Current.MainWindow as MainWindow;
if (mainWin.GridMain.Background ==  b)
     MDark.IsChecked = true;

我不得不提到 MDark 是一个单选按钮。 条件永远不会成立。 我很感激帮助。 :D

【问题讨论】:

  • 为什么?您已经在设计时设置或定义了这些颜色。使用设计器比较颜色。或者将画笔定义为资源(​​例如x:Key="DefaultBackgroundBrush")并在应用程序中重用它们(例如Grid.Background="{StaticResource DefaultBackgroundBrush}"
  • 您正在比较实例引用。请改用Equals()。或者比较Color 的值。

标签: c# wpf xaml


【解决方案1】:

您正在比较 SolidColorBrush 实例,它们显然不一样。而是比较实际的颜色值:

var c = (Color) ColorConverter.ConvertFromString ("#424242");
MainWindow mainWin = Application.Current.MainWindow as MainWindow;
if (((SolidColorBrush) mainWin.GridMain.Background).Color == c) 
{
    MDark.IsChecked = true;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多