您可以在组合框上对 SelectedItem 进行数据绑定。如果我理解您的描述,您有一组十六进制字符串和一个名为 Color 的 SolidColorBrush 属性。以下代码在更改选定项目时更新 Color 属性。
XAML:
<Window x:Class="SelItemTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:SelItemTest="clr-namespace:SelItemTest"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<SelItemTest:StringToBrushConverter x:Key="StringToBrush" />
</Window.Resources>
<StackPanel Background="{Binding Path=Color}">
<ComboBox
ItemsSource="{Binding Path=Colors}"
SelectedItem="{Binding Path=Color, Converter={StaticResource StringToBrush}}">
<ComboBox.ItemTemplate>
<DataTemplate>
<Border Background="{Binding}" Height="20" Width="100" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
</Window>
后面的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
namespace SelItemTest
{
public partial class Window1 : Window, INotifyPropertyChanged
{
public Window1()
{
InitializeComponent();
Colors = new List<string>();
Colors.Add(Brushes.Red.ToString());
Colors.Add(Brushes.Blue.ToString());
Colors.Add(Brushes.Yellow.ToString());
Color = Brushes.Yellow;
DataContext = this;
}
public List<string> Colors { get; set;}
private SolidColorBrush _color;
public SolidColorBrush Color
{
get { return _color; }
set
{
_color = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Color"));
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
public class StringToBrushConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Color color = (Color)ColorConverter.ConvertFromString(value.ToString());
SolidColorBrush scb = new SolidColorBrush(color);
return scb;
}
#endregion
}
}