【问题标题】:WPF Combox using Itemteplate with multiple sourcesWPF Combobox 使用带有多个源的 Itemtemplate
【发布时间】:2020-04-05 18:43:27
【问题描述】:

我正在尝试使用 ItemTemplate 制作 WPF 组合框。我的想法是像本教程https://www.wpf-tutorial.com/list-controls/combobox-control/ 一样在组合框中创建项目,但略有不同。我有 2 个列表,我想将其用作源。包含 Rectangles = 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>

有可能吗?如何?谢谢。

【问题讨论】:

  • 如果你想要每个项目中的两个属性,为什么要这两个列表?为什么你感兴趣的两件事不是一个类的属性。然后,您可以绑定这个新类的一个列表或 observablecollection。这可能会暴露一个画笔属性(使用您的颜色的纯色画笔)和一个字符串属性。 (或者您可以将颜色名称设为字符串并在视图中使用转换器来构建纯色画笔。)
  • ASh,这只是一个错字,我更正了。
  • 安迪,我可以使用任何集合,这些列表只是源数据的示例,我可以将我的数据放在任何集合中,或者我可以为它创建新类,我什么都没有,但是我知道什么解决方案是最好的。

标签: c# wpf combobox binding


【解决方案1】:

你应该用一个字符串和纯色画笔作为属性创建一个新类

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

然后应该创建此类的 ObservableCollection 并将其绑定到您的组合框。

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>

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 2014-11-26
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    相关资源
    最近更新 更多