如何从数据库填充 WPF window

How to populate WPF window from database

我想在加载新 window 时自动从数据库加载一些数据以填充一些文本框和组合框。

例如,当我单击 window1 中的按钮时,window1 将显示一个新的 window window2 并将 ID 传递给 window2(查询数据库需要id)。 我该怎么做?

谢谢,

使用Entity Framework.

按照以下教程操作..

http://blogs.msdn.com/b/wriju/archive/2010/06/09/ado-net-entity-framework-4-0-loading-data-in-4-ways.aspx

https://msdn.microsoft.com/en-us/library/aa697427(v=vs.80).aspx

这只是您可以执行的操作的一个非常简单的示例:

MainWindow.xaml

<Window x:Class="WpfApplication1.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>
        <Button Name="btn1" Click="btn1_Click" Content="Button" Margin="10,10,361,283"></Button>
    </Grid>
</Window>

MainWindow.xaml.cs

  private void btn1_Click(object sender, RoutedEventArgs e)
        {
            Window2 win2 = new Window2(1);
            win2.Show();
        }

Window2.xaml

<Window x:Class="WpfApplication1.Window2"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window2" Height="300" Width="300">
    <Grid Margin="0,0,170,249">
        <TextBox Name="txtBox1" Margin="18,160,-18,-173"></TextBox>
        <TextBox Name="txtBox2" Margin="18,119,-18,-134"></TextBox>
        <TextBox Name="txtBox3" Margin="18,76,-18,-93"></TextBox>
        <TextBox Name="txtBox4" Margin="18,36,-18,-50"></TextBox>
    </Grid>
</Window>

Window2.xaml.cs

public partial class Window2 : Window
    {
        public Window2(int Id)
        {
            InitializeComponent();
            ReadDataFromDB(Id);
        }

        public void ReadDataFromDB(int Id)
        {

            //read your data
            txtBox1.Text = "Some value 1";
            txtBox2.Text = "Some value 2";
            txtBox3.Text = "Some value 3";
            txtBox4.Text = "Some value 4";
        }
    }

1)Create ui elements in the window

2)Create a model class with the required fields.

3)While clicking the button in window1 pass the id to the constructor of the next window.

4).Using the id query the database based on your need.Get the results and bind the fields to the ui elements values.

5).These database querying and all can be written inside your constructor or window load event.

您可以使用 MVVM 完成此操作。无需编写额外的代码来将值设置为 ui。