问题:谁能请提供完整的代码示例,说明一个怎样编程方式更改数据绑定WPF组合框的的SelectedItem不使用MyComboBox.SelectedIndex?如何编程设置数据绑定WPF组合框的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;
}
}
}
}
类似的问题:我当然在网上搜索了第一,但没有发现任何帮助了我。
- 更改内部视图模型一个枚举绑定组合框的的SelectedItem(MSDN)
- 编程设置组合框的SelectedItem在WPF(3.5SP1)(Stack Overflow)
伟大的微调,非常感谢您的帮助! – Lernkurve 2010-08-17 11:39:10
很高兴我能帮到你。 :)我添加了第二种绑定方法,如果你想尝试一下。该代码没有经过测试,所以我希望我还有一些运气。 – Mizipzor 2010-08-17 11:56:54
现在我在this.DataContext = myPersonlist(它不需要ComboBox有一个名称)和FindAncestor方法之间撕裂,它根本不需要代码隐藏。 – Lernkurve 2010-08-17 14:34:53