C# 获取WPF中填充矩形的RGB颜色

C# 获取WPF中填充矩形的RGB颜色,c#,wpf,visual-studio,C#,Wpf,Visual Studio,在我的WPF项目中,我有一个矩形。运行时,矩形的填充-颜色会发生变化 如果用户单击矩形,则应获得该矩形的rgb值 我知道我可以将其保存为画笔,如下所示: Brush brush = rectangle.Fill; 但我不知道如何从中得到RGB值 我需要的是: labelRed.Text = brush.red; labelGreen.Text = brush.green; labelBlue.Text = brush.blue; 您应该从属性中获取SolidColorBrus

在我的WPF项目中,我有一个
矩形
。运行时,
矩形的
填充
-颜色会发生变化

如果用户单击
矩形
,则应获得该
矩形
rgb值

我知道我可以将其保存为
画笔
,如下所示:

Brush brush = rectangle.Fill;
但我不知道如何从中得到RGB值

我需要的是:

labelRed.Text = brush.red;    
labelGreen.Text = brush.green;    
labelBlue.Text = brush.blue;

您应该从属性中获取
SolidColorBrush
,然后从
SolidColorBrush
中获取颜色结构,现在颜色对象具有and属性


您可以使用矩形的属性,从中获取画笔
var color=((SolidColorBrush)rectangle.Fill)以防它不是很明显。颜色结构具有属性R、G和B感谢您的回答,这是非常好的理解!修改了代码,以显示在
rectangle.Fill
不是SolidColorBrush的情况下如何避免InvalidCastException。当它根本没有被指定,或者它包含不同的画笔类型(例如ImageBrush)时,可能会发生这种情况。
SolidColorBrush solidColorBrush = rectangle.Fill as SolidColorBrush;

if (solidColorBrush != null)
{
    Color color = solidColorBrush.Color;
    byte r = color.R;
    byte g = color.G;
    byte b = color.B;

    MessageBox.Show($"R{r}\nG{g}\nB{b}");
}