5

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

1 回答 1

4

确保您已将DataContext窗口设置为视图模型类的实例:

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

通常,您通常不会在视图模型中定义与 UI 相关的内容,例如颜色。这些东西通常直接在视图中定义,没有任何绑定。但是您当然可以绑定到这样的Brush属性。

于 2017-06-01T19:54:13.687 回答