在具有不同颜色的组合框项目上添加其他信息

时间:2016-10-15 10:29:58

标签: c# wpf xaml combobox

首先这是我的代码背后:

conn.Open();
DataTable data = new DataTable();
string sql = "SELECT * FROM itemsTbl";
SQLiteCommand command = new SQLiteCommand(sql, conn);
SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
adapter.Fill(data);
cmb_items.ItemsSource = data.DefaultView;
cmb_items.DisplayMemberPath = "item_description";
cmb_items.SelectedValuePath = "item_id";
conn.Close();

这是我的xaml:

<ComboBox x:Name="cmb_items"
    VerticalAlignment="Top" VerticalContentAlignment="Center" 
    FontSize="14" 
    Foreground="#666"
    Height="30" 
    Margin="20,20,20,10" 
    IsEditable="True" 
    ItemsSource="{Binding}" 
    TextSearch.Text="{Binding Path=item_description}" />

它很好并且正常工作但是我想在组合框项目上添加一些信息,以便用户已经知道是否有库存或是通过包或个人或类似的东西。如果可能,将零库存的颜色更改为红色。

这是我目前的组合框:

ComboBox1

这是我的目标(photoshop):

enter image description here

我只需要在组合框项目上提供额外信息,但如果用户点击该项目,则只显示item_description,如下所示:

enter image description here

老实说,我不知道该怎么做,我试图添加一个combobox.itemtemplate,但是当我选择一个项目时,它会显示&#34; System.Data.DataRowView&#34;。组合框也是可搜索的。我应该改变我的方法并通过循环添加项目吗?我是wpf的新手,之前我尝试过wpf,但因为工作繁忙而停止了,所以任何帮助都非常感谢谢谢!

1 个答案:

答案 0 :(得分:0)

1.为了显示额外信息,您可以使用ItemTemplate和DataTrigger:

     <ComboBox.ItemTemplate>
            <DataTemplate DataType="wpfApplication1:Item">
                <StackPanel Orientation="Horizontal">
                    <TextBlock  Text="{Binding item_id}"/>
                    <TextBlock  Text="{Binding item_description}" Margin="300,0,0,0">
                        <TextBlock.Style>
                            <Style>
                                <Style.Triggers>
                                    <DataTrigger Binding="{Binding item_description}" Value="0">
                                        <Setter Property="TextBox.Foreground" Value="Red"/>
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </TextBlock.Style>
                    </TextBlock>
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>

2.为了对其他项目中的所选项目进行不同的显示,您可以使用DataTemplateSelector:https://stackoverflow.com/a/33421573/3955716