c# - 将表值绑定到组合框时出错 - wpf
问题描述
我有一个组合框,它应该从数据库中动态绑定数据。
组合框的来源是一个可观察的集合。
我遵循的步骤:
声明了一个组合框:
<ComboBox ItemsSource="{Binding populatecombobox.modeltogetusername }" Width="155" Margin="18,15,618,0"/>
创建了一个类来从数据库中获取数据:
public class populatetab2combobox { public ObservableCollection<comboboxdata> modeltogetusername { get; set; } public void getdatausinglinq() { using (Operations_Productivity_ToolEntities context = new Operations_Productivity_ToolEntities()) { var a1 = from t1 in context.Test_ImportedAuditdata select t1; if (modeltogetusername == null) modeltogetusername = new ObservableCollection<comboboxdata>(); foreach (var a in a1.GroupBy(x => x.username).Select(x => x.FirstOrDefault())) { modeltogetusername.Add(new comboboxdata { username = a.username }); } } } }
在视图模型中实例化上述类
public class ViewModel: INotifyPropertyChanged { private populatetab2combobox _populatecombobox = new populatetab2combobox(); public populatetab2combobox populatecombobox { get { return _populatecombobox; } set { if (value != _populatecombobox) { _populatecombobox = value; OnPropertyChanged("populatecombobox"); } } } public ViewModel() { _populatecombobox.getdatausinglinq(); }
}
预期的输出是:
Ren1
Ren2
实际输出为
Namespace.Model.comboxdata
Namespace.Model.comboxdata
解决方案
您正在获取 ToString() 方法的输出,并且您正在绑定到 comboboxdata 类的实例,而不是其中的用户名。
您有 2 个选项。首先,您可以将您的 xaml 更改为此通知我们如何绑定到项目模板中的属性。
<ComboBox ItemsSource="{Binding populatecombobox.modeltogetusername }" Width="155" Margin="18,15,618,0">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding username}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
其次,您可以覆盖组合框数据上的 ToString() 方法以返回用户名
推荐阅读
- javascript - 检查 ngIf 角度指令中的字符串列表中是否存在字符串的有效方法是什么
- reactjs - useRef、useMemo、useCallback 钩子的生产用例是什么?
- typescript - 为什么这两个映射元组类型不相等?
- java - 如何从包含具有重复参数名称的方法的 .WSDL 文件创建 Java SOAP Web 服务?
- c# - 尽管模型有效,但 TryValidateModel 返回 false
- reactjs - 用 onClick 反应 useCallback 不起作用。渲染子组件
- java - 如何在单链表中连接字符串和整数
- r - 用索引替换布尔规则中字符串的一部分
- c# - 如何通过 C# 以编程方式从 Prefetch 或此类文件夹中删除需要管理权限的文件
- java - 检查是否已使用特定索引 - 按位?