1

我有 3 个TexBoxes、Buttons 和DataGrid在我的窗口中。当我将数据输入TextBox并单击按钮时,它应该添加到DataGrid。我需要一个代码来说明如何添加、删除和获取数据。我是 wpf 的新手,请帮我写代码。这是我的 Xaml 代码

  <Window x:Class="simpledatagrid.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="IDDATA" Height="350" Width="525">
<Grid  >
    <DataGrid BorderBrush="Black" BorderThickness="2" AutoGenerateColumns="True" Name="dgsample" Margin="200,10,10,75"></DataGrid>

    <Label  Content="ID :" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="26" Width="27"/>
    <Label  Content="Name :" HorizontalAlignment="Left" Margin="10,60,0,0" VerticalAlignment="Top" Height="26" Width="48"/>
    <Label  Content="Salary :" HorizontalAlignment="Left" Margin="10,110,0,0" VerticalAlignment="Top" Height="26" Width="47"/>

    <TextBox Name="tb1" HorizontalAlignment="Left" Height="20" Margin="60,10,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="100"/>
    <TextBox Name="tb2" HorizontalAlignment="Left" Height="20" Margin="60,60,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="100"/>
    <TextBox Name="tb3" HorizontalAlignment="Left" Height="20" Margin="60,110,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="100"/>

    <Button Content="Get" HorizontalAlignment="Left" Margin="10,190,0,0" VerticalAlignment="Top" Width="75" Click="Get_Click" />
    <Button Content="Add" HorizontalAlignment="Left" Margin="10,230,0,0" VerticalAlignment="Top" Width="75" Click="Add_Click" />
    <Button Content="Delete" HorizontalAlignment="Left" Margin="10,270,0,0" VerticalAlignment="Top" Width="75" Click="Delete_Click" />
</Grid>

这是我的 .cs 代码

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
         List<User> users = new List<User>();
                    users.Add(new User() { Id = 101, Name = "gin", Salary = 10 });
                    users.Add(new User() { Id = 102, Name = "alen", Salary = 20 });
                    users.Add(new User() { Id = 103, Name = "scott", Salary = 30 });

                    dgsample.ItemsSource = users;
            }

    private void Get_Click(object sender, RoutedEventArgs e)
    {

    }

    private void Add_Click(object sender, RoutedEventArgs e)
    {

    }

    private void Delete_Click(object sender, RoutedEventArgs e)
    {

    }
    }  
}
4

4 回答 4

1

首先,您可以使用 ObservableCollection 代替 List。因为 ObservableCollection 默认有 INotifyCollectionChanged。ObservableCollection 是 TwoWayBinding。

ObservableCollection<User> users = new  ObservableCollection<User>();
public MainWindow()
{
    InitializeComponent();

                users.Add(new User() { Id = 101, Name = "gin", Salary = 10 });
                users.Add(new User() { Id = 102, Name = "alen", Salary = 20 });
                users.Add(new User() { Id = 103, Name = "scott", Salary = 30 });

                dgsample.ItemsSource = users;
}

private void Get_Click(object sender, RoutedEventArgs e)
{
     if (this.tb1.Text != string.Empty) { User currentUser = users.Single(select => select.Id == Int32.Parse(this.tb1.Text)); this.tb2.Text = currentUser.Name; this.tb3.Text = currentUser.Salary; } 
}

private void Add_Click(object sender, RoutedEventArgs e)
{
      users.Add(new User() { Id = 105, Name = "gin5", Salary = 100 });
}

private void Delete_Click(object sender, RoutedEventArgs e)
{
   users.RemoveAt(0);
}
于 2013-10-17T08:24:52.193 回答
0

定义用户类:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Salary { get; set; }

    public User()
    {

    }

    public User(int id, string name, int salary)
    {
        Id = id;
        Name = name;
        Salary = salary;
    }
}

然后在您的 MainWindow.xaml.cs 文件中将您的 List 更改为 ObservableCollection (您需要添加;

using System.Collections.ObjectModel;// 编辑

进而:

ObservableCollection<User> users;

public MainWindow()
{
    users = new ObservableCollection<User>();
    users.Add(new User() { Id = 101, Name = "gin", Salary = 10 });
    users.Add(new User() { Id = 102, Name = "alen", Salary = 20 });
    users.Add(new User() { Id = 103, Name = "scott", Salary = 30 });

    InitializeComponent();
    dgsample.ItemsSource = users;
}


private void Add_Click(object sender, RoutedEventArgs e)
{
    users.Add(new User(){Id = Int.Parse(tb1.Text), Name = tb2.Text, Salary = Int.Parse(tb3.Text)});
}

private void Delete_Click(object sender, RoutedEventArgs e)
{
    users.RemoveAt(dgSample.SelectedIndex);
}

// you can get what you need just selected proper User proprety
private void Get_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show(( (User)dgSample.Items[dgSample.SelectedIndex]).Name);
}
于 2013-10-17T08:22:56.943 回答
0

定义一个ObservableCollection要设置的属性ItemsSourceDataGrid并在您想从 中添加/删除任何项目时对其进行更新DataGrid。更新集合将更新数据网格

        public MainWindow()
        {
            InitializeComponent();
            Users = new ObservableCollection<User>;
            Users.Add(new User() {Id = 101, Name = "gin", Salary = 10});
            Users.Add(new User() {Id = 102, Name = "alen", Salary = 20});
            Users.Add(new User() {Id = 103, Name = "scott", Salary = 30});

            dgsample.ItemsSource = Users;
        }

        private ObservableCollection<User> Users { get; set; }

        private void Add_Click(object sender, RoutedEventArgs e)
        {
            Users.Add(new User() {Id = int.Parse(tb1.Text), Name = tb2.Text, Salary = tb3.Text});
        }

另外,作为建议,添加/删除功能是内置的DataGrid,设置 CanUserAddRowsCanUserDeleteRowstrue 允许用户直接将项目添加到 中DataGrid,因此您可能不需要文本框和按钮来添加/删除

  <DataGrid AutoGenerateColumns="True" CanUserAddRows="True" CanUserDeleteRows="True"></DataGrid>
于 2013-10-17T08:23:12.970 回答
0

如果您是 WPF 新手,您应该从WPF 方式开始。在 WPF 中,您应该操作绑定到 UI 的数据,而不是直接操作 UI。这种设计模式被称为MVVM

在您的情况下,您将有一个类(称为ViewModel),其中将包含您的User项目集合(称为Model)。

public class MainWindowViewModel
{
    public MainWindowViewModel()
    {
         Users = new ObservableCollection<User>();
                users.Add(new User() { Id = 101, Name = "gin", Salary = 10 });
                users.Add(new User() { Id = 102, Name = "alen", Salary = 20 });
                users.Add(new User() { Id = 103, Name = "scott", Salary = 30 });
    }

    public ObservableCollection<User> Users { get; set; }
}

在您的MainWindow(称为View)代码隐藏中,您应该做的就是将其设置DataContextMainWindowViewModel.

public MainWindow()
{
    InitializeComponent();
    DataContext = new MainWindowViewModel();
}

在窗口本身中,将集合绑定到ViewModelUsers中的属性

 <DataGrid BorderBrush="Black" BorderThickness="2" AutoGenerateColumns="True" Name="dgsample" Margin="200,10,10,75" ItemsSource="{Binding Users}"></DataGrid>

至于您的TextBoxes,因为它们旨在创建一个新的,您可以在ViewModelUser上拥有另一个User属性

public User NewUser { get; set; }

并将它们绑定到您User班级中的匹配属性

<TextBox Name="tb1" HorizontalAlignment="Left" Height="20" Margin="60,10,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="100" Text="{Binding Path=NewUser.Id}"/>
<TextBox Name="tb2" HorizontalAlignment="Left" Height="20" Margin="60,60,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="100" Text="{Binding Path=NewUser.Name}"/>
<TextBox Name="tb3" HorizontalAlignment="Left" Height="20" Margin="60,110,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="100" Text="{Binding Path=NewUser.Salary}"/>

添加新的后User,清除它的属性。

至于你的按钮,它们应该通过Commands与ViewModel通信,然后只使用它实现的简单和方法来操作集合本身。你可以在这里了解更多AddRemove

希望这可以帮助

于 2013-10-17T08:28:41.167 回答