c# - 如何将数据表绑定(bind)到 wpf 可编辑组合框 : selectedItem showing System. Data.DataRowView

标签 c# wpf data-binding wpf-controls binding

我将一个数据表绑定(bind)到一个组合框并在 itemTemplate 中定义了一个数据模板。我可以在组合框下拉列表中看到所需的值,我在 selectedItem 中看到的是 System.Data.DataRowView 这里是我的代码:

 <ComboBox Margin="128,139,123,0" Name="cmbEmail" Height="23" VerticalAlignment="Top" TabIndex="1" ToolTip="enter the email you signed up with here" IsEditable="True" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding}">

            <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                      <TextBlock Text="{Binding Path=username}"/>
                </StackPanel>

            </DataTemplate>
        </ComboBox.ItemTemplate>

后面的代码是这样的:

 if (con != null)
 {
    con.Open();
    //users table has columns id | username | pass
    SQLiteCommand cmd = new SQLiteCommand("select * from users", con);
    SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
    userdt = new DataTable("users");
    da.Fill(userdt);
    cmbEmail.DataContext = userdt;

 }

我一直在寻找类似 SelectedValueTemplate 或 SelectedItemTemplate 的东西来做同样类型的数据模板,但我没有找到。

我想问一下是我做错了什么还是组合框绑定(bind)的已知问题?
如果我的代码有问题,请指出正确的方向。
感谢阅读本文

最佳答案

默认情况下,组合框将在所选项目上调用 ToString() 以获取要显示的值 - 因为您绑定(bind)到 DataRowView,所以结果就是类型(ToString() 的默认行为)

您实际想要显示的是所选项目的用户名属性,为此您可以设置 DisplayMemberPath组合框的“用户名”

(此外,如果您这样做,您可能会发现您也可以摆脱自定义数据模板,因为用户名也将用于填充每个项目。)


回应您的评论:

我不想成为那些程序员,但“它可以在我的机器上运行”。

我的 XMAL 是:

 <ComboBox Name="cmbEmail" 
            Height="23" 
            VerticalAlignment="Top" 
            TabIndex="1" 
            ToolTip="enter the email you signed up with here"
            IsEditable="True"
            IsSynchronizedWithCurrentItem="True" 
            ItemsSource="{Binding}"
            DisplayMemberPath="username">
  </ComboBox> 

我的代码是:

public partial class Window1 : Window
{
    public Window1()
    {
        Users = new DataTable("users");
        Users.Columns.Add("username");

        Users.Rows.Add(CreateDataRow("Fred"));
        Users.Rows.Add(CreateDataRow("Bob"));
        Users.Rows.Add(CreateDataRow("Jim"));

        InitializeComponent();

        cmbEmail.DataContext = Users;
    }

    public DataTable Users { get; private set; }

    private DataRow CreateDataRow(string userName)
    {
        DataRow dr = Users.NewRow();
        dr["username"] = userName;

        return dr;
    }
}

关于c# - 如何将数据表绑定(bind)到 wpf 可编辑组合框 : selectedItem showing System. Data.DataRowView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2865231/

相关文章:

c# - IDE 用于 Linux 上的 C# 开发?

c# - 为什么我在此文件夹上收到 UnauthorizedAccessException?

c# - 设置 InkCanvas.InkPresenter 绑定(bind)

c# - 验证后删除小数 @ WPF 文本框

wpf - ScrollViewer 抢夺焦点

wpf - 用于数据绑定(bind)的 IntelliSense 不起作用

javascript - 编辑对象时理解 angularjs $apply 和 $scope

C# 实时 try catch

c# - 如何选择 serviceStatus.dwWaitHint 的值?

c# - WPF 图表控件