简体   繁体   English

如何在Avalonia中绑定颜色

[英]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. 在WPF中,如何将颜色(如背景颜色)绑定到viewmodel属性更令人困惑。

Are there other ways to bind Colors in Avalonia ? 还有其他方法可以在Avalonia中绑定颜色吗?

Or is this example a good way ? 或者这个例子是一个好方法?

Avalonia View Avalonia视图

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

Make sure that you have set the DataContext of the window to an instance of your view model class: 确保已将窗口的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>

In general you don't usually define UI related things such as colours in the view model though. 通常,您通常不会在视图模型中定义与UI相关的内容,例如颜色。 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. 但你当然可以绑定到这样的Brush属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM