使用具有多个源的 Itemtemplate 的 WPF 组合框

WPF Combox using Itemteplate with multiple sources

我正在尝试使用 ItemTemplate 制作 WPF 组合框。我的想法是像本教程 https://www.wpf-tutorial.com/list-controls/combobox-control/ 中那样在组合框中创建项目,但略有不同。我有 2 个列表,我想将其用作源。包含矩形颜色的列表 = colorList,以及包含字符串的列表 TextBlocks = classesList

List<System.Windows.Media.SolidColorBrush> colorList = new List<System.Windows.Media.SolidColorBrush>
List<string> classesList = new List<string>


    <ComboBox Name="cmbClasses" ItemsSource=" ??? " SelectionChanged="cmbClasses_SelectionChanged"  Margin="10" >
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Rectangle Name="rectSelectedClassColor" Fill=" ??? " Width="16" Height="16" Margin="0,2,5,2" />
                    <TextTextBlock Name="cboxSelectedClass" Text=" ??? " MinWidth="50" />
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

可能吗?如何?谢谢。

您应该制作一个新的 class 并将字符串和纯色画笔作为属性

public class NewClass
{
 public string Name {get;set;}
 public SolidColorBrush Brush {get;set;}
}

然后应该制作一个 ObservableCollection class 并将其绑定到您的组合框。

ObservableCollection<NewClass> Source = new ObservableCollection<NewClass>();

XAML 可能看起来像这样。

<ComboBox ItemSource = "{Binding Source}">
  <ComboBox.ItemTemplate>
    <DataTemplate>
     <StackPanel>
       <Rectangle Fill = "{Binding Brush}"/>
       <TextBlock Text = "{Binding Name}"/>
     </StackPanel>
    </DataTemplate>
  </ComboBox.ItemTemplate>
</ComboBox>