Search code examples
c#backgroundwindows-store-appsbrushsolidcolorbrush

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

Solution

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