x:bind not works in color value

MG Bhadurudeen 626 Reputation points

Hi, I have a viewmodel for setting theme colors. setting the primary color in xaml using Binding works without any issue, even during design time, it shows the default color in the page/grid. However if I change the Binding to x:Bind it does not work. How to solve this? where am I doing wrong?

       <themeViewModels:ThemeViewModel x:Key="ThemeViewModel"/>

<Grid Grid.Column="1" 
              DataContext="{StaticResource ThemeViewModel}">
                    <SolidColorBrush x:Name="ss" Color="{x:Bind PrimaryColor, Mode=OneWay}"/>
Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Daniele 1,996 Reputation points

    With x:Bind you have to do the following

    • set your ThemeViewModel as Page.DataContext and bind Color to _viewModel.PrimaryColor <Page.DataContext>
      <Grid Grid.Column="1">
      <SolidColorBrush x:Name="ss" Color="{x:Bind _viewModel.PrimaryColor, Mode=OneWay}"/>
    • declare field _viewModel in your Page code behind private ThemeViewModel _viewModel;
    • use DataContextChanged event: add this code in your page constructor DataContextChanged += (sender, args) =>
      if (_viewModel == args.NewValue || !(args.NewValue is ThemeViewModel themeViewModel)) return;
      _viewModel = themeViewModel;

1 additional answer

Sort by: Most helpful
  1. Roy Li - MSFT 32,731 Reputation points Microsoft Vendor


    Welcome to Micorsoft Q&A!

    There is something that you might misunderstand with data-binding.

    • The x:bind markup will automatically use the code-behind as the Datacontext. If you are using x:bind, it will only look up for properties from the code-behind instead of the view model you put in the page resource. If you want to set your view model as Datacontext, you could use Binding markup
    • The correct way to set DataContext in Xaml is to call Page.Datatext not Page.resources.
    • Another thing is that please also check the PrimaryColor property to make sure it is a Color object.

    I have a code snippet that works correctly, you could check it.

        <local:ThemeViewModel x:Name="ThemeViewmodel"/>  
    <Grid >  
        <Grid Grid.Column="1" >  
                <SolidColorBrush x:Name="ss" Color="{Binding mycolor, Mode=OneWay}"/>  

    You could also refer to these documents for more information about data binding: Data binding overview, Data binding in depth

    Thank you.