如何在Avalonia中绑定颜色

10
在WPF中,如何将颜色(例如背景颜色)绑定到视图模型属性可能会有些困惑。在Avalonia中,是否存在其他绑定颜色的方法?或者这个示例是一个好的方式呢?
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

public class MainWindowViewModel
{
    private IBrush _textbox3Foreground;

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

    public MainWindowViewModel()
    {
         Textbox3Foreground = Brushes.DarkOliveGreen;            
    }
}
1个回答

7

确保您已将窗口的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属性。

谢谢,我明白了。我只是在玩Avalonia,它很棒! - EinApfelBaum

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接