C# 如何从代码隐藏绑定到XAML资源颜色
我很难将代码后面的颜色绑定到XAML中定义为资源的颜色。 该绑定对于文本(aka Message)工作良好,但对于XAML中定义的颜色,我无法完成绑定。 这是我正在使用的精简代码 XAML:C# 如何从代码隐藏绑定到XAML资源颜色,c#,wpf,xaml,binding,C#,Wpf,Xaml,Binding,我很难将代码后面的颜色绑定到XAML中定义为资源的颜色。 该绑定对于文本(aka Message)工作良好,但对于XAML中定义的颜色,我无法完成绑定。 这是我正在使用的精简代码 XAML: <Window x:Class="WpfApplication3.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<SolidColorBrush x:Key="BlueBrush" Color="#FFCFEDFF" />
<SolidColorBrush x:Key="GreenBrush" Color="#FFE5EFC8" />
</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding List, ElementName=UI}" x:Name="listBox" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.Background>
>>> <SolidColorBrush Color="{StaticResource {Binding Path=Background}}"/> <<< Here is my problem <<<
</Grid.Background>
<TextBlock Text="{Binding Message}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
>>>创建一个名为BackgroundBrush
的新属性,并使用此代码将字符串转换为笔刷:
public Brush BackgroundBrush => return (SolidColorBrush)new BrushConverter().ConvertFromString(this.Background);
仅使用binding关键字绑定到它(无需使用StaticResource):
只需将背景
绑定到笔刷
属性
<Grid>
<ListBox ItemsSource="{Binding List, ElementName=UI}" x:Name="listBox" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Background="{Binding Background}">
<TextBlock Text="{Binding Message}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
请看这里:我以前看过这篇文章,但它是关于动态创建资源的。这是一种不同的方法。实际上,我希望在某个地方预定义笔刷,而不是为每一行创建新的笔刷。因为我不想降低性能。@Thawa您不需要为每一行创建新的SolidColorBrush。而是重用笔刷实例。当两条线应具有相同的颜色时,请将相同的SolidColorBrush实例指定给其背景属性。除此之外,您仍然可以将它们定义为资源,并通过(刷子)Resources[“BlueBrush”]
在代码隐藏中访问它们。通过视图模型属性引用笔刷实例的成本并不比为其资源键保存字符串高。
{Binding BackgroundBrush}
<Grid>
<ListBox ItemsSource="{Binding List, ElementName=UI}" x:Name="listBox" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Background="{Binding Background}">
<TextBlock Text="{Binding Message}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
buffer = new ObservableCollection<Line>();
listBox.ItemsSource = buffer;
buffer.Add(new Line("Line1", new SolidColorBrush(Colors.Blue)));
buffer.Add(new Line("Line2", new SolidColorBrush(Colors.Green)));
}
private ObservableCollection<Line> buffer;
public class Line
{
private string _message;
private Brush _background;
public Line(String message, Brush background)
{
this._message = message;
this._background = background;
}
public string Message
{
get { return _message; }
set { _message = value; }
}
public Brush Background
{
get { return _background; }
set { _background = value; }
}
}
}