【发布时间】:2010-08-17 09:45:08
【问题描述】:
问题:谁能提供一个完整的代码示例,说明如何在不使用 MyComboBox.SelectedIndex 的情况下以编程方式更改数据绑定 WPF ComboBox 的 SelectedItem?
代码示例:这是我目前拥有的。
XAML:
<Window x:Class="Wpf.ComboBoxDemo.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">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ComboBox Name="MyComboBox" DisplayMemberPath="LastName" SelectedIndex="0"/>
</Grid>
</Window>
代码隐藏:
using System.Collections.ObjectModel;
using System.Windows;
namespace Wpf.ComboBoxDemo
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ObservableCollection<Person> myPersonList = new ObservableCollection<Person>();
Person personJobs = new Person("Steve", "Jobs");
Person personGates = new Person("Bill", "Gates");
myPersonList.Add(personJobs);
myPersonList.Add(personGates);
MyComboBox.ItemsSource = myPersonList;
// How do I programmatically select the second Person, i.e. "Gates"?
// The best pratice must be to somehow to set something like IsCurrentlySelected on the model, so the view update automatically. But how?
MyComboBox.SelectedIndex = 1; // This works, but is there no way without using the index?
}
private class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}
}
}
类似问题:我当然先上网搜索,但没有找到任何帮助我的东西。
- 更改 ViewModel 中枚举绑定组合框的 SelectedItem (MSDN)
- 在 WPF (3.5sp1) 中以编程方式设置 ComboBox SelectedItem (Stack Overflow)
【问题讨论】:
标签: c# wpf data-binding combobox