簡體   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