EinApfelBaum
EinApfelBaum

Reputation: 157

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

Upvotes: 10

Views: 10530

Answers (1)

mm8
mm8

Reputation: 169150

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.

Upvotes: 7

Related Questions