Skip to main content
 首页 » 编程设计

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

2024年02月24日37sharpest

我将一个数据表绑定(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; 
    } 
}