In a WPF window, I have a Textbox bound to a DataGrid, already filled with data. When I select a different row, the text in the textbox changes correctly. However when the WPF is loaded, there is no selection at first, so the textbox stays empty. Only when I actually select a row, the binding to the textbox takes place.
How can I achieve that when the form is loaded, the first row of the DataGrid is automaticly selected and so the textbox is filled.
Here is how I bind the textbox to the datagrid (XAML):
<TextBox x:Name="txtContactNaam" Grid.Column="1" Grid.Row="11" Grid.ColumnSpan="1" Margin="10,10,10,10" Text = "{Binding ElementName = dgContacten, Path = SelectedItem.[Naam],
Mode = TwoWay, UpdateSourceTrigger = PropertyChanged}" ></TextBox>
Thanks for your help.
A bit more code:
public partial class wpfTest_2 : Window
{ DataTable dtContacten;
DataSet dsContacten = new DataSet("Contacten");
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MaakTabellen();
VulTabellen();
dgContacten.ItemsSource = dtContacten.DefaultView;
}
private void MaakTabellen()
{
dtContacten = new DataTable("Contacten");
dsContacten.Tables.Add(dtContacten);
dtContacten.Columns.Add("Naam", typeof(string));
dtContacten.Columns.Add("Voornaam", typeof(string));
}
private void VulTabellen()
{
ToevoegenDataContacten("Vanderbeke", "Michel");
ToevoegenDataContacten("Maes", "Maddy");
ToevoegenDataContacten("Pieters", "Jan");
}
private void ToevoegenDataContacten(string naam, string voornaam)
{
DataRow nieuwContact = dsContacten.Tables["Contacten"].NewRow();
nieuwContact["Naam"] = naam;
nieuwContact["Voornaam"] = voornaam;
dsContacten.Tables["Contacten"].Rows.Add(nieuwContact);
}
}
<DataGrid x:Name="dgContacten" Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="6" Grid.RowSpan="10" Margin="10,10,10,10" RowBackground="LightYellow" AlternatingRowBackground="LightBlue" ItemsSource="{Binding Table}"
SelectedItem="{Binding Row, Mode=TwoWay}"></DataGrid>
<TextBox x:Name="txtContactNaam" Grid.Column="1" Grid.Row="11" Grid.ColumnSpan="1" Margin="10,10,10,10" Text = "{Binding ElementName = dgContacten, Path = SelectedItem.[Naam],
Mode = TwoWay, UpdateSourceTrigger =PropertyChanged}" ></TextBox>
<TextBox x:Name="txtContactVoornaam" Grid.Column="1" Grid.Row="12" Grid.ColumnSpan="1" Margin="10,10,10,10" Text = "{Binding ElementName = dgContacten, Path = SelectedItem.[Voornaam],
Mode = TwoWay, UpdateSourceTrigger = PropertyChanged}"></TextBox>
Hope this clarifies my problem.
you can set selected row after assigning ItemsSource:
dgContacten.ItemsSource = dtContacten.DefaultView;
dgContacten.SelectedIndex = 0;
btw, the following bindings are not doing anything:
ItemsSource="{Binding Table}"
SelectedItem="{Binding Row, Mode=TwoWay}"
because
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.