繁体   English   中英

加载 WPF 表单时选择数据网格的第一行

[英]Selecting first row of datagrid when WPF form is loaded

在 WPF window 中,我有一个绑定到 DataGrid 的文本框,已经填充了数据。 当我 select 不同的行时,文本框中的文本正确更改。 但是,当 WPF 加载时,一开始没有选择,因此文本框保持为空。 只有当我实际 select 一行时,才会发生与文本框的绑定。

如何在加载表单时实现这一点,自动选择 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>

谢谢你的帮助。

多一点代码:

public partial class wpfTest_2 : Window

{ 数据表 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>

希望这能澄清我的问题。

您可以在分配 ItemsSource 后设置选定的行:

dgContacten.ItemsSource = dtContacten.DefaultView;
dgContacten.SelectedIndex = 0;

顺便说一句,以下绑定没有做任何事情:

ItemsSource="{Binding Table}" 
SelectedItem="{Binding Row, Mode=TwoWay}"

因为

  • 您在代码中重置 ItemsSource
  • 你没有分配 DataContext
  • 属性表和行不存在

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM