所以,我有: TextBox和Button
我如何在datagrid中添加新值?
例如,TextBox.Text ="示例文本"
我点击按钮和DataGrid
sample text
输入TextBox sample text 2
然后单击按钮,然后单击
的数据网格:
sample text
sample text 2
等...
请帮忙!
答案 0 :(得分: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);
}
答案 1 :(得分:0)
将datagrid的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>