Search code examples
c#xamluwpviewmodel

UWP: How to bind a property from a base class in XAML


For the past couple of days I have been tinkering trying to find a solution for the given situation below.

I have a base class AppColors containing different color properties:

public class AppColors
{
    public static Brush ColorTransparent    { get; private set; }
    public static Brush ColorBlack          { get; private set; }
        
    public AppColors()
    {
        ColorTransparent = new SolidColorBrush(U.Hex2Color("#00ffffff"));
        ColorBlack       = new SolidColorBrush(U.Hex2Color("#ff000000"));
    }
}   

My ColorPage ViewModel uses the AppColors class as its base:

public class ColorPageViewModel: AppColors
{
    public static Brush ColorCustom   { get; private set; }

    public ColorPageViewModel ()
    {
        ColorCustom = new SolidColorBrush(U.Hex2Color("#ffff1234"));
    }
}

Inside the ColorPage XAML I want to make a binding to the ColorBlack property from the base color class.

<Page
    x:Class="MyApp.Pages.ColorPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="using:MyApp"
    xmlns:vm="using:MyApp.ViewModels"
    mc:Ignorable="d">

    <Page.DataContext>
        <vm:ColorPageViewModel />
    </Page.DataContext>

    <!-- the property ColorBlack can not be retrieved, but no error is given -->
    <Grid Background="{Binding ColorBlack}"></Grid>
</Page>

The binding to the ColorBlack property is not used when I run the application. I was expecting it to be retrieved from the base color class.

I can fix the problem by declaring a page resource and use that as my source for the binding, but that defeats the whole purpose of using the color class as a base.

<Page.Resources>
    <local:AppColors x:Key="AppColors" />
</Page.Resources>

<Page.DataContext>
    <vm:ColorPageViewModel />
</Page.DataContext>

<!-- the property ColorBlack works now! -->
<Grid Background="{Binding ColorBlack, Source={StaticResource AppColors}}"></Grid>

Any advice on how to access the properties from the base color class?


Solution

  • Any advice on how to access the properties from the base color class?

    ColorBlack is not an instance/local property of the view model.

    Use {x:Bind} when you bind to static properties:

    <Grid Background="{x:Bind vm:ColorPageViewModel.ColorBlack}"></Grid>