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

巧了我就是萌 提交于 2019-12-25 01:44:26

问题


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. So I have this XAML in a User Control:

<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")

How can I get the actual value of the background rather than just its type?

UPDATE

I'm not understanding just how to implement SLaks' answer; I've tried:

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

回答1:


Expanding on SLaks answer:

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. 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.




回答2:


Because SolidColorBrush doesn't override ToString().

To extract that actual color, cast it to SolidColorBrush and use the Color property.



来源:https://stackoverflow.com/questions/27215615/why-is-the-canvas-background-property-a-generic-solidcolorbrush-instead-of-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!