我無法將來自後面的代碼的顏色綁定到在XAML中定義爲資源的顏色。 該綁定對於文本(又名消息)工作正常,但我無法完成XAML中定義的顏色。 這裏是我正在使用的精簡代碼。如何從後面的代碼綁定到XAML資源顏色
的XAML:
<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>
背後的代碼:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication3
{
public partial class MainWindow : Window
{
private ObservableCollection<Line> buffer;
public MainWindow()
{
InitializeComponent();
buffer = new ObservableCollection<Line>();
listBox.ItemsSource = buffer;
buffer.Add(new Line("Line1", "BlueBrush"));
buffer.Add(new Line("Line2", "GreenBrush"));
}
public class Line
{
private string _message;
private string _background;
public Line(String message, String background)
{
this._message = message;
this._background = background;
}
public string Message
{
get { return _message; }
set { _message = value; }
}
public string Background
{
get { return _background; }
set { _background = value; }
}
}
}
}
在這裏看到:http://stackoverflow.com/q/13262037/1136211 – Clemens
我以前看過這篇文章,但它是關於dynamicaly創建資源。這是一種不同的方法。 – thowa