简体   繁体   English

为什么“画布”的“背景”属性是通用的“ SolidColorBrush”而不是实际的颜色?

[英]Why is the Canvas' Background property a generic “SolidColorBrush” instead of an actual color?

I want to respond to a tap on a canvas and store the value of the canvas' background in app settings so that I can assign that value to the AppBar / Command Bar. 我想响应画布上的轻击,并将画布背景的值存储在应用程序设置中,以便可以将该值分配给AppBar / Command Bar。 So I have this XAML in a User Control: 所以我在用户控件中有此XAML:

<StackPanel Orientation="Horizontal">
    <Canvas Background="Aqua" Width="20" Height="20" VerticalAlignment="Center" Tapped="CanvasColor_Tapped"></Canvas>
    <TextBlock Text="Aqua" VerticalAlignment="Center" Tapped="CanvasColor_Tapped" ></TextBlock>
</StackPanel>

..and the handler is: ..并且处理程序是:

private void CanvasColor_Tapped(object sender, TappedRoutedEventArgs treArgs)
{
    if (sender is Canvas)
    {
        Brush colour = ((Canvas)sender).Background;
        String brushColorAsStr = colour.ToString();
        IAppSettings appSettings;
        if (App.SaveSettingsLocally)
        {
            appSettings = new AppSettingLocal();
        }
        else
        {
            appSettings = new AppSettingsRoaming();
        }
        appSettings.SaveSetting(VisitsConsts.APP_BAR_COLOR_SETTING, brushColorAsStr);
    }
}

Yet the value of brushColorAsStr is simply "Windows.UI.XAML.Media.SolidColorBrush" (I'm expecting it to be something like "Magenta" or "Windows.UI.XAML.Media.SolidColorBrush.Magenta") 但是brushColorAsStr的值只是“ Windows.UI.XAML.Media.SolidColorBrush”(我希望它是“ Magenta”或“ Windows.UI.XAML.Media.SolidColorBrush.Magenta”之类的东西)

How can I get the actual value of the background rather than just its type? 如何获得背景的实际值,而不只是背景类型?

UPDATE UPDATE

I'm not understanding just how to implement SLaks' answer; 我不仅仅了解如何实现SLaks的答案; I've tried: 我试过了:

Brush brsh = ((Canvas) sender).Background;
//var color = (SolidColorBrush)brsh.
//var color = ((SolidColorBrush) sender).Color;
//var color = (SolidColorBrush).((Canvas)sender).Color;

Because SolidColorBrush doesn't override ToString() . 因为SolidColorBrush不会覆盖ToString()

To extract that actual color, cast it to SolidColorBrush and use the Color property. 要提取该实际颜色,请将其转换为SolidColorBrush并使用Color属性。

Expanding on SLaks answer: 在SLaks上扩展答案:

Example: 例:

var canvas = sender as Canvas;
var brush = canvas.Background as SolidColorBrush;
var color = brush.Color;

Please note that this works because you set the default of a single, solid color. 请注意,这是可行的,因为您设置了单色的默认颜色。 That's why it's a SolidColorBrush . 这就是为什么它是SolidColorBrush的原因。 You can set it to any kind of brush, linear gradient, textures or whatever you like. 您可以将其设置为任何类型的笔刷,线性渐变,纹理或任何您喜欢的颜色。 For obvious reasons, the code above will not work if you set anything but a single color solid brush. 出于明显的原因,如果您只设置单色纯色笔刷,则上面的代码将不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM