Binder des TextBox sur le SelectedItem d'un DataGrid
:salut:
Je cherche à binder deux TextBox en fonction de ma ligne sélectionnée dans mon DataGrid.
J'ai beau lire et relire mon code, je n'arrive pas à voir où ça déconne :koi:
La vue :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <DockPanel>
<DataGrid Name="person" ItemsSource="{Binding Persons}" SelectedItem="{Binding SelectedPerson}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"></DataGridTextColumn>
<DataGridTextColumn Header="FirstName" Binding="{Binding FirstName}"></DataGridTextColumn>
<DataGridTextColumn Header="Birth date" Binding="{Binding BirthDate}"></DataGridTextColumn>
<DataGridTextColumn Header="Age" Binding="{Binding Age}"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
<StackPanel>
<TextBox Name="name" Text="{Binding SelectedPerson.Name}" Width="100" Margin="10"></TextBox>
<TextBox Name="firstname" Text="{Binding SelectedPerson.FirstName}" Width="100"></TextBox>
</StackPanel>
</DockPanel> |
Le code behind :
Code:
1 2 3 4 5 6 7
| public MainWindow()
{
InitializeComponent();
PersonsVM p = new PersonsVM();
p.Persons.Add(new Person("Germez", "Sébastien", new DateTime(1988, 04, 13)));
DataContext = p;
} |
Et les classes PersonsVM et Person :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| public class PersonsVM : INotifyPropertyChanged
{
public List<Person> Persons { get; set; }
public Person SelectedPerson { get; set; }
public PersonsVM()
{
this.Persons = new List<Person>();
this.SelectedPerson = new Person();
}
private void RaisePropertyChanged(String property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class Person
{
public string Name { get; set; }
public string FirstName { get; set; }
public DateTime BirthDate { get; set; }
public int Age { get; set; }
public Person() { }
public Person(string name, string firstName, DateTime birthDate)
{
this.Name = name;
this.FirstName = firstName;
this.BirthDate = birthDate;
DateTime today = DateTime.Today;
int age = today.Year - birthDate.Year;
if (today < birthDate.AddYears(age))
age--;
this.Age = age;
}
} |
Si quelqu'un pouvait m'éclairer... Je n'ai aucune erreur mais lorsque je sélectionne ma ligne, mes deux TextBox restent vides :(
:merci: