-3

所以,我有:TextBox 和 Button

我如何在数据网格中添加新值?

例如 TextBox.Text = "示例文本"

我单击按钮,然后 DataGrid

sample text

输入文本框sample text 2

并单击按钮,然后

数据网格:

sample text

sample text 2

ETC...

请帮忙!

4

2 回答 2

0

将数据网格的 itemssource 绑定到 observablecollection。然后,如果您单击按钮,请执行类似的操作

myitemssource.add(new myitemtype());

在一个非常简单的情况下:

public partial class TestWindow : Window
{
    public TestWindow()
    {
        InitializeComponent();
        DataContext = this;
    }

    ObservableCollection<Person> _persons;
    public ObservableCollection<Person> Persons
    {
        get { return _persons ?? (_persons = new ObservableCollection<Person>()); }
        set { _persons = value; }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var split = txtBox.Text.Split(' ');
        try
        {
            Persons.Add(new Person() { FirstName = split[0], LastName = split[1], Age = Int32.Parse(split[2]) });
        }
        catch (IndexOutOfRangeException)
        {
        }
        catch (FormatException)
        {
        }
    }
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

<Window x:Class="ItemsControlTest.TestWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="TestWindow" Height="300" Width="300">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="auto"/>
    </Grid.ColumnDefinitions>
    <TextBox Name="txtBox" Text="Firstname lastname 10"/>
    <Button Grid.Column="1" Click="Button_Click" Content="click me"/>

    <DataGrid Grid.Row="1" Grid.ColumnSpan="2" ItemsSource="{Binding Path=Persons}">

    </DataGrid>
</Grid>

于 2012-08-09T13:08:45.547 回答
0

假设您在 xaml 中的窗口上有一个数据网格、一个文本框和一个按钮,代码隐藏:

ObservableCollection<string> list = new ObservableCollection<string>();
    public Window()
    {
        InitializeComponent();
        datagrid1.ItemsSource = list;

    }
    private void button1_Click(object sender, RoutedEventArgs e)
    {
        list.Add(textBox1.Text);
    }
于 2012-08-09T13:01:38.193 回答