好吧我不明白为什么WPF无法显示组合框项目的“显示成员”,但可以执行“选定值”。奇怪的是,我可以明确地创建显示成员,但不能恢复。在我的示例中,我简化了将使用ADO.NET来填充项目源的真实世界示例,但概念是相同的。我正在生成一个在运行时从sql语句生成的组合框。我想获得一件事物的价值,但要显示别的东西。是否有一些额外的绑定或定制我缺少或只是错误的成员的.NET?我只想让'显示...'选择回来。如果这似乎不可能有点奇怪。当我选择'价值'时,所有我回来,所以我知道在转移中丢失了一些东西。Combobox不能正确显示“显示成员”?
任何想法?
XAML:
<Window x:Class="WPFComboBoxTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<ComboBox x:Name="cmb" Width="100" Height="50"/>
<TextBlock Height="100"/>
<Button x:Name="btn" Content="Click" Click="btn_Click" Width="50"/>
</StackPanel>
C#代码背后:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
namespace WPFComboBoxTest
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
BindComboBox(cmb);
}
public void BindComboBox(ComboBox cbx)
{
DataTable dt = new DataTable();
dt.Columns.Add("Value", typeof(string));
dt.Columns.Add("Id", typeof(int));
dt.Rows.Add("Display of One", 1);
dt.Rows.Add("Display of Two", 2);
dt.Rows.Add("Display of Three", 3);
dt.Rows.Add("Display of Four", 4);
cbx.ItemsSource = dt.DefaultView;
cbx.DisplayMemberPath = dt.Columns["Value"].ToString();
cbx.SelectedValuePath = dt.Columns["Id"].ToString();
}
private void btn_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Selected Value works: " + cmb.SelectedValue
+ "\n\nSelect Display does not though?: " + cmb.DisplayMemberPath
);
}
}
}
(facepalm)它非常简单。 cmb.DisplayMemberPath需要是cmb.Text。 “文本”是我需要显示向用户显示的显示成员的属性。 – djangojazz 2012-08-14 21:53:00