基本上你自己在代码中回答了这个问题。
Grid.Background 是 DependencyProperty 的 Type Brush。这意味着我们可以将bind 任何Brush 发送到Grid。
您如何选择执行此绑定取决于您,并且可以从中获得许多很酷的样式/功能。
这是一个非常基本的 ViewModel 来演示这一点。
using System.ComponentModel;
using System.Windows.Media;
namespace Question_Answer_WPF_App
{
public class BackgroundViewModel : INotifyPropertyChanged
{
private readonly SolidColorBrush DefaultBrush = new SolidColorBrush(Colors.BlueViolet);
private Brush background;
public event PropertyChangedEventHandler PropertyChanged;
public BackgroundViewModel() => background = DefaultBrush;
public Brush Background
{
get => background;
set
{
background = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Background)));
}
}
}
}
那么你可以这样使用它......
<Grid Name="myGrid"
Background="{Binding Background}">
...
只是为了帮助你,我给你做了一个更好的。这是 ViewModel 中的一些预设画笔,以及 View 中的 Grid。您可以按原样复制和粘贴此内容,无需任何代码,它会起作用。 (请注意,我故意使用了 3 种不同的画笔;SolidColorBrush、ImageBrush 和 LinearGradientBrush。还有更多,任何一种都可以使用。)
视图模型
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace Question_Answer_WPF_App.ViewModels
{
public class BackgroundViewModel : INotifyPropertyChanged
{
private Brush selectedBackground;
public BackgroundViewModel()
{
var brushes = new List<Brush>
{
new SolidColorBrush(Colors.BlueViolet),
new ImageBrush(new BitmapImage(new Uri("http://i.stack.imgur.com/jGlzr.png", UriKind.Absolute))),
new LinearGradientBrush(Colors.Black, Colors.White, 45)
};
BackgroundOptions = brushes;
SelectedBackground = BackgroundOptions.FirstOrDefault();
}
public event PropertyChangedEventHandler PropertyChanged;
public IEnumerable<Brush> BackgroundOptions { get; }
public Brush SelectedBackground
{
get => selectedBackground;
set
{
selectedBackground = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedBackground)));
}
}
}
}
查看
<Window x:Class="Question_Answer_WPF_App.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ViewModels="clr-namespace:Question_Answer_WPF_App.ViewModels"
mc:Ignorable="d"
Title="MainWindow"
Height="500"
Width="800">
<Window.DataContext>
<ViewModels:BackgroundViewModel />
</Window.DataContext>
<Grid Background="{Binding SelectedBackground}">
<ComboBox ItemsSource="{Binding BackgroundOptions}"
SelectedItem="{Binding SelectedBackground}"
Width="250"
Height="40"
VerticalAlignment="Top"
HorizontalAlignment="Left"
Margin="12">
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid Background="{Binding}"
Height="40"
Width="200" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
</Window>
屏幕截图