[英]WPF C# ComboBox Display Value
我不能问这个问题。 我已经在3个不同的论坛中提出了要求,并且在Google上搜索了大约一个星期,现在什么也没有。 因此,让我在这里再次尝试,看看是否以其他方式提出要求可以帮助您...
使用MahApps.Metro窗口的WPF C#MetroWindow-组合框-状态代码(美国50个州)我创建了一个数据集并将数据集拖到XAML中的组合框中。 这是XAML
<ResourceDictionary>
<CollectionViewSource x:Key="StatesViewSource"
Source="{Binding States, Source={StaticResource PRx}}" />
</ResourceDictionary>
在GRID内部,我设置了数据上下文:
<Grid DataContext="{StaticResource StatesViewSource}">
然后组合框
<ComboBox x:Name="CbState"
SelectedValuePath="StateCode"
ItemsSource="{Binding}"
DisplayMemberPath="StateCode" />
现在,就是这样,我停止了,它可以正常工作。 我在组合框中找到了州代码; 但是,这不是问题,也不是我需要解决的问题。 我需要做的是查询数据库,找到患者,然后将地址返回到窗口。 除组合框外,每个字段都填充在窗口中。 即使患者的状态代码为MA,也始终默认为列表中的第一个状态-AL-值。
因此,SQL有效。 组合框提取值。 但是我无法将组合框默认设置为通过SQL返回的MA。
这也是我正在使用的一些C#代码。
private void ReturnPatient()
{
var patIdReturn = TxtPatId.Text;
var patSiteId = TxtTSiteCode.Text;
var preSql = Settings.Default.GetPatientProfile;
var param = " @p1 = '" + patIdReturn + "', @p2 = '" + patSiteId + "';";
var sql = preSql + param;
var connectionString = Settings.Default.Dbconn;
using (var conn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sql, conn))
{
try
{
conn.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
TxtFirstName.Text = reader[0] as string;
TxtMi.Text = reader[1] as string;
TxtLastName.Text = reader[2] as string;
TxtLegacy.Text = reader[3] as string;
DobPicker.SelectedDate = reader[4] as DateTime? ?? new DateTime();
TxtPhone.Text = reader[5] as string;
TxtAddr1.Text = reader[6] as string;
TxtAddr2.Text = reader[7] as string;
TxtCity.Text = reader[8] as string;
TbState.Text = reader[9] as string;
// trying a tbox instead of combobox, but this is where I want the Combobox for State.
TxtZip.Text = reader[10] as string;
//break for single row or you can continue if you have multiple rows...
break;
}
Log.Debug("Command executed and reader completed for ReturnPatient()");
}
catch (SqlException ex)
{
// error handling
}
finally
{
// logging
}
}
}
我尝试了CbState.SelectedItem,CbState.SelectedValue,CbState.DisplayMemeber等...
拜托,我知道这是必须的。 请帮忙
真诚的
迷失在ComboBox地狱:)
看来这很简单,但您缺少基本要点。 如果单击组合框,是否可以看到作为绑定项填充的50个州名称? 如上所述,检查reader [9]的值确实是MA。 我建议尝试像reader [“ yourcolumnname”]这样更具体的方式以避免混淆。
并尝试CbState.SelectedText =“ MA”;
或CbState.Text =“ MA”;
selected-前缀可能意味着它是用户必须有意选择的前缀。
并确保在XML中选择了index = -1。 如果索引= 0,则组合框将默认第一个填充项AL。
最后,如果您只需要将已经固定的50个州名称放入组合框,为什么不简化代码结构而不进行绑定,例如
CbState.Items.Add("AL");
....
CbState.Items.Add("MA");
CbState.Items.Add("NY");
对于计算机,添加已经固定的50个名称比绑定要简单得多,而且速度更快。 如果您不需要做更高层次的绑定工作。
作为无关紧要的小问题,应该以正确的方式关闭阅读器和连接。
cb_State.SelectedItem = (cb_State.ItemsSource as List<YourStateCodeClass>).Where(s=>s.StateCode == reader[9] as string).First();
但我看不到您的StateCode类,但是您使用DisplayMemberPath
等。
如果只是字符串,您可以使用
cb_State.SelectedItem = (cb_State.ItemsSource as List<string>).Where(s => s == reader[9] as string).First();
并删除DisplayMemberPath
和SelectedValuePath
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.