Question: Quelqu'un peut-il s'il vous plaît fournir un exemple de code complet qui montre comment on modifie par programme le SelectedItem d'un ComboBox WPF lié aux données sans utiliser MyComboBox.SelectedIndex?Comment définir par programme SelectedItem d'un ComboBox WPF lié aux données?
Exemple de code : Voici ce que j'ai actuellement.
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>
code-behind:
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;
}
}
}
}
Des questions similaires: J'ai bien sûr des recherches sur Internet en premier lieu, mais rien trouvé qui m'a aidé.
- Modification du SelectedItem d'un combobox lié enum-inside ViewModel (MSDN)
- définir par programme SelectedItem ComboBox dans WPF (3.5sp1) (Stack Overflow)
Un grand coup de coude, merci beaucoup pour votre aide! – Lernkurve
Content de pouvoir aider. :) J'ai ajouté la deuxième méthode de liaison, si vous voulez l'essayer. Ce code n'est pas testé non plus alors j'espère que j'ai de la chance. – Mizipzor
Maintenant, je suis déchiré entre this.DataContext = myPersonlist (qui n'a pas besoin de la ComboBox pour avoir un nom) et votre approche FindAncestor qui n'a pas besoin de code-behind du tout. – Lernkurve