我希望在一个C# Winforms应用程序中创建可编辑的ListView,在其中用户可以双击单元格以更改其内容。如果有人能够提供一些指导和/或示例,那将是非常好的。我不想使用任何商业产品。
我希望在一个C# Winforms应用程序中创建可编辑的ListView,在其中用户可以双击单元格以更改其内容。如果有人能够提供一些指导和/或示例,那将是非常好的。我不想使用任何商业产品。
你问的问题不正确 :)
ListView不是正确的控件。使用DataGridView控件。它可以配置成看起来就像ListView,但支持单元格的原地编辑。
<Window.Resources>
<ResourceDictionary>
<DataTemplate x:Key="NameHeader">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Name" VerticalAlignment="Center" Margin="10,0,0,0" />
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="NameCell">
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding Path=Name}" VerticalAlignment="Center" Margin="10,0,0,0" />
</StackPanel>
</DataTemplate>
</ResourceDictionary>
</Window.Resources>
<Grid>
<ListView x:Name="lvwList" Height="200" VerticalAlignment="Top" ItemsSource="{Binding Path=SourceObjectCollection}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" HeaderTemplate="{StaticResource NameHeader}" CellTemplate="{StaticResource NameCell}" Width="140" />
</GridView>
</ListView.View>
</ListView>
</Grid>
Nick Hanshaw
是的,使用一个DataGridView。
不仅可以编辑单元格,而且如果你声明一个泛型列表,其中T是你想在网格中显示的类,你可以将DataSource设置为该列表,当你编辑GridView时,实际上是自动地编辑了列表!
DataGridView是你的好朋友,SourceGrid是另一种选择。
我最近遇到了这个问题。在得到Simon Gillbee的提示后,我意识到可以将DataGridView配置成类似ListView的样式,于是我开始寻找一个合理的解决方案来实现这一目标。以下代码对我非常有效。源代码在这里。
class GridLineDataGridView : DataGridView
{
public GridLineDataGridView()
{
this.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
int rowHeight = this.RowTemplate.Height;
int h = this.ColumnHeadersHeight + rowHeight * this.RowCount;
int imgWidth = this.Width - 2;
Rectangle rFrame = new Rectangle(0, 0, imgWidth, rowHeight);
Rectangle rFill = new Rectangle(1, 1, imgWidth - 2, rowHeight);
Rectangle rowHeader = new Rectangle(2, 2, this.RowHeadersWidth - 3, rowHeight);
Pen pen = new Pen(this.GridColor, 1);
Bitmap rowImg = new Bitmap(imgWidth, rowHeight);
Graphics g = Graphics.FromImage(rowImg);
g.DrawRectangle(pen, rFrame);
g.FillRectangle(new SolidBrush(this.DefaultCellStyle.BackColor), rFill);
g.FillRectangle(new SolidBrush
(this.RowHeadersDefaultCellStyle.BackColor), rowHeader);
int w = this.RowHeadersWidth - 1;
for (int j = 0; j < this.ColumnCount; j++)
{
g.DrawLine(pen, new Point(w, 0), new Point(w, rowHeight));
w += this.Columns[j].Width;
}
int loop = (this.Height - h) / rowHeight;
for (int j = 0; j < loop + 1; j++)
{
e.Graphics.DrawImage(rowImg, 1, h + j * rowHeight);
}
}
}
只需从 DataGridView
继承并重写 OnPaint
方法。
您可以更改控件的各种属性以适应您的需求和偏好。
对于那些需要帮助将自定义控件纳入其项目的人,请查看 此处。
也许这可以帮到你: