Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind color in Avalonia

In WPF it was a bit more confusing how to bind colors, like background color to a viewmodel property.

Are there other ways to bind Colors in Avalonia ?

Or is this example a good way ?

Avalonia View

<Window xmlns="https://github.com/avaloniaui"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Button.Views.MainWindow"
    Title="Button" Width="700">
  <StackPanel Grid.Column="2" Orientation="Vertical" Gap="8" Margin="10"> 
      <TextBox Name="Textbox3" Text="{Binding Textbox3Text}" Foreground="{Binding Textbox3Foreground}"/>    
  </StackPanel>
</Window>

Avalonia ViewModel

public class MainWindowViewModel
{
    private IBrush _textbox3Foreground;

    public IBrush Textbox3Foreground
    {
        get { return _textbox3Foreground; }
        set
        {
            this.RaiseAndSetIfChanged(ref _textbox3Foreground, value);
        }
    }    

    public MainWindowViewModel()
    {
         Textbox3Foreground = Brushes.DarkOliveGreen;            
    }
}
like image 383
EinApfelBaum Avatar asked Jun 01 '17 19:06

EinApfelBaum


1 Answers

Make sure that you have set the DataContext of the window to an instance of your view model class:

<Window xmlns="https://github.com/avaloniaui"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Button.Views.MainWindow"
    Title="Button" Width="700">
    <Window.DataContext>
        <local:MainWindowViewModel />
    </Window.DataContext>
    <StackPanel Grid.Column="2" Orientation="Vertical" Gap="8" Margin="10">
        <TextBox Name="Textbox3" Text="{Binding Textbox3Text}" Foreground="{Binding Textbox3Foreground}"/>
    </StackPanel>
</Window>

In general you don't usually define UI related things such as colours in the view model though. These kind of things are usually defined directly in the view without any bindings. But you can certainly bind to a Brush property like this.

like image 169
mm8 Avatar answered Oct 24 '22 05:10

mm8