在 WPF 中创建一个 DataGrid,其列类型等于 WinForm 的 DataGridViewButtonColu
本文关键字:类型 DataGridViewButtonColu WinForm DataGrid 创建 WPF 一个 | 更新日期: 2023-09-27 17:57:23
在WinForm中,我可以通过循环以编程方式在DataGridView列上添加行,让我们这样说
private void rowsAdder()
{
for(int u = 0; u<= 10; u++)
{
classSelect.Rows.Add("Number " + u);
//classSelect is a name of a DataGridView, where the first column is a DataGridViewButtonColumn
}
}
那么我的问题是:
-WPF 中在数据网格中添加行的相同方法是什么(使用循环Rows.Add()
等)?
-如何将列类型设置为按钮列?
如果这有帮助,我正在使用 .NET 4.5
这是一个非常简单的例子:
<Window x:Class="DataGridUpdateSourceTriggerOneWay.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DataGridUpdateSourceTriggerOneWay"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid x:Name="DataGrid1"
IsReadOnly="False"
AutoGenerateColumns="False"
CanUserAddRows="False"
ItemsSource="{Binding data}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Field">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Name, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" Width="Auto"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Length of Field">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Length, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" Width="Auto"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
这是您的 DataGrid,它的 ItemsSource 绑定到存在于以下代码隐藏中的数据:
public partial class MainWindow : Window
{
public ObservableCollection<Data> data { get; set; }
public MainWindow()
{
InitializeComponent();
data = new ObservableCollection<Data>();
data.Add(new Data() { Name = "Data1", Length = 1 });
data.Add(new Data() { Name = "Data2", Length = 2 });
this.DataContext = this;
}
}
集合需要通知其绑定视图元素其内容已更改(添加或删除项),这是ObservableCollection<Data>
的工作。
下面是 Data 类:
public class Data : INotifyPropertyChanged
{
private string _Name;
public string Name
{
get { return _Name; }
set
{
_Name = value;
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
private int _Length;
public int Length
{
get { return _Length; }
set
{
_Length = value;
PropertyChanged(this, new PropertyChangedEventArgs("Length"));
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
INotifyPropertyChanged
接口是用于特定目的的观察者模式实现的一部分:通知订阅者发布服务器上的属性值刚刚更改。因此,更改集合现有实例上的这两个属性(名称或长度)将导致视图更新。
如果您需要有关此的更多详细信息,请告诉我。
哦,我忘了,你会如何添加新行?只需处理放置在视图上某处的按钮的 Click 事件,并将新的数据实例添加到数据收集中。
前任:
data.Add(new Data() { Name = "Data3", Length = 3 });