首页 > 解决方案 > 组合框选定值返回 System.Data.DataRowView

问题描述

我有一个 SQL 表,其中包含用于填充 WPF 组合框的列“AreaCode”和“Description”。但是当我在组合框上选择一个项目时,它会在组合框文本上显示 System.Data.DataRowView。下面是组合框的 xaml。

                    <ComboBox x:Name="AreaComboBox" Grid.Row="3" Grid.Column="1" Width="300" Margin="5" IsEditable="True" ItemsSource="{Binding}" SelectedValuePath="Description">
                        <ComboBox.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">
                                    <TextBlock x:Name="Area" Text="{Binding AreaCode}"/>
                                    <TextBlock Text=" "/>
                                    <TextBlock x:Name="Description" Text="{Binding Description}"/>
                                </StackPanel>
                            </DataTemplate>
                        </ComboBox.ItemTemplate>
                    </ComboBox>

组合框使用简单的 c# 代码填充:AreaComboBox.ItemsSource = dataSet.Area.AsDataView();

我注意到的是,如果我将 IsEditable 更改为 False,这不是问题,只有当它为 true 时才会出现问题。

有人可以帮我弄清楚为什么它返回“System.Data.DataRowView”而不是我选择的项目的文本吗?如果有解决方案会更好:)

我非常乐意提供更多细节。

标签: c#wpfcomboboxvisual-studio-2019

解决方案


您可以为 StackPanel 设置一个事件MouseLeftButtonDown="StackPanel_MouseDown",然后使用下面的代码来更新 ComboBox 的文本。

 private void StackPanel_MouseDown(object sender, MouseButtonEventArgs e)
    {
        string tb1 = ((TextBlock)(sender as StackPanel).Children[0]).Text;
        string tb2 = ((TextBlock)(sender as StackPanel).Children[1]).Text;
        string tb3 = ((TextBlock)(sender as StackPanel).Children[2]).Text;

        AreaComboBox.Text = tb1 +"   "+ tb3;

    }

推荐阅读