WPF DataGrid:使单元格只读

swift

1个回答

写回答

18699217339

2025-08-30 16:30

+ 关注

微软
微软

WPF DataGrid:使单元格只读

WPF(Windows Presentation Foundation)是微软的一种用于创建Windows客户端应用程序的技术。其中的DataGrid控件是一种常用的数据展示和编辑工具,可以方便地展示和编辑数据。在某些情况下,我们希望某些单元格只能展示数据而不能编辑,这时就需要将这些单元格设置为只读。

下面我们将介绍如何在WPF DataGrid中使单元格只读,并给出一个简单的案例代码。

首先,我们需要在XAML文件中添加一个DataGrid控件,并绑定数据源。可以通过ItemsSource属性将数据源与DataGrid关联起来。例如,我们可以将一个ObservableCollection类型的集合作为数据源,其中T是我们自定义的数据模型。

xaml

<Window x:Class="WpfApp.MAInWindow"</p> XMLns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

XMLns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="WPF DataGrid" Height="450" Width="800">

<Grid>

<DataGrid x:Name="MyDataGrid" ItemsSource="{Binding MyCollection}" AutoGenerateColumns="False">

<!-- 在这里添加列定义 -->

</DataGrid>

</Grid>

</Window>

在代码中,我们需要定义DataGrid的列。可以通过DataGrid.Columns属性来定义列,例如可以使用DataGridTextColumn来定义一个文本列。在这个例子中,我们定义了两列,分别是Name和Age。

xaml

<DataGrid.Columns>

<DataGridTextColumn Header="Name" Binding="{Binding Name}" IsReadOnly="True"/>

<DataGridTextColumn Header="Age" Binding="{Binding Age}" IsReadOnly="True"/>

</DataGrid.Columns>

在上面的代码中,我们通过设置IsReadOnly属性为True,将这两列设置为只读。这样,用户就不能在这两列中编辑数据了。

案例代码:

下面是一个完整的案例代码,展示了如何在WPF DataGrid中使单元格只读。

csharp

using System.Collections.ObjectModel;

using System.ComponentModel;

using System.Windows;

namespace WpfApp

{

public partial class MAInWindow : Window

{

public ObservableCollection<Person> MyCollection { get; set; }

public MAInWindow()

{

InitializeComponent();

// 初始化数据源

MyCollection = new ObservableCollection<Person>()

{

new Person() { Name = "John", Age = 25 },

new Person() { Name = "Alice", Age = 30 },

new Person() { Name = "Bob", Age = 35 }

};

// 将数据源与DataGrid绑定

DataContext = this;

}

}

public class Person : INotifyPropertyChanged

{

private string _name;

public string Name

{

get { return _name; }

set

{

_name = value;

OnPropertyChanged("Name");

}

}

private int _age;

public int Age

{

get { return _age; }

set

{

_age = value;

OnPropertyChanged("Age");

}

}

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string propertyName)

{

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

}

}

}

上面的代码中,我们定义了一个Person类作为数据模型,其中包含Name和Age属性。在MAInWindow的构造函数中,我们初始化了一个ObservableCollection类型的集合作为数据源,并将其与DataGrid进行绑定。同时,我们将Name和Age列的IsReadOnly属性设置为True,使它们只读。

这样,就完成了在WPF DataGrid中使单元格只读的操作。希望本文对你在WPF开发中使用DataGrid控件有所帮助!

举报有用(4分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号