更好的方法是将列表绑定到您创建的对象。这样,您可以指定 DisplayMemberPath(您所看到的)和 SelectedValuePath(您的程序内部值)的属性。
这是您的主要 XAML 代码。请注意,按钮的单击方法将显示 ComboBox 的当前选定值。这将使以后的事情变得容易。希望这不是矫枉过正,但它展示了一些使 WPF 变得简单的原则。
namespace WPFListBoxSample {
public partial class Window1 : Window
{
WPFListBoxModel model = new WPFListBoxModel();
public Window1()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Window1_Loaded);
}
void Window1_Loaded(object sender, RoutedEventArgs e)
{
GetData();
this.DataContext = model;
}
public void GetData()
{
//SqlConnection myConnection = new SqlConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "ProgramsList.sdf");
SqlConnectionStringBuilder str = new SqlConnectionStringBuilder();
str.DataSource="192.168.1.27";
str.InitialCatalog="NorthWnd";
str.UserID="sa";
str.Password="xyz";
SqlConnection myConnection = new SqlConnection(str.ConnectionString);
SqlDataReader myReader = null;
myConnection.Open();
SqlDataReader dr = new SqlCommand("SELECT CategoryId, CategoryName FROM Categories ORDER BY CategoryName DESC", myConnection).ExecuteReader();
while (dr.Read())
{
model.Categories.Add(new Category { Id = dr.GetInt32(0), CategoryName = dr.GetString(1) });
}
myConnection.Close();
}
private void myButton_Click(object sender, RoutedEventArgs e)
{
if (this.myCombo.SelectedValue != null)
MessageBox.Show("You selected product: " + this.myCombo.SelectedValue);
else
MessageBox.Show("No product selected");
}
}
}
XAML
<Grid>
<StackPanel>
<ComboBox x:Name="myCombo" ItemsSource="{Binding Categories}" DisplayMemberPath="CategoryName" SelectedValuePath="Id" />
<Button x:Name="myButton" Content="Show Product" Click="myButton_Click"/>
</StackPanel>
</Grid>
您自己的用于表示类别的对象
namespace WPFListBoxSample
{
public class Category
{
public int Id { get; set; }
public string CategoryName { get; set; }
}
}
注意 {get; 套
最后,让很多事情变得简单的一点胶水是将所有数据放入模型中并绑定到模型。这是工作 WPF 的方式。
using System.Collections.Generic;
namespace WPFListBoxSample
{
public class WPFListBoxModel
{
private IList<Category> _categories;
public IList<Category> Categories
{
get
{
if (_categories == null)
_categories = new List<Category>();
return _categories; }
set { _categories = value; }
}
}
}