c# - WPF - 如何获取 DataGrid 中每一行的高度?
问题描述
我有一个在单元格中启用了 TextWrapping 的 DataGrid。这意味着行没有相同的高度。我的问题是如何遍历行并获得每行的高度?DataGrid 的外观如下:
这是数据网格代码:
public ObservableCollection<Article> persons = new ObservableCollection<Article>();
for(int i = 0; i < 35; i++)
{
persons.Add(new Article("Restless legs syndrome and tis correlation with other sleep problems in the general adult population of Japan",
"Minori Enomoto, Lan Li, Sayaka Aritake, Yukihiro Nagase, Tatsuhiko Kaji, Hirokuni Tagaya, Masato Matsuura, Yoshitaka Kaneita, Takashi Ohida, Makoto Uchiyama",
"Sleep and Biological Rhythms",
4));
}
dgMain.ItemsSource = persons;
我是这样计算的:
private void btnTest_Click(object sender, RoutedEventArgs e)
{
int k = 0;
var rows = GetDataGridRows(dgMain);
foreach (DataGridRow r in rows)
{
var rowHeight = r?.ActualHeight;
k++;
}
MessageBox.Show(k.ToString());
}
这是文章类:
public class Article
{
private string _title;
public string Title
{
get { return this._title; }
set { this._title = value; }
}
private string _authors;
public string Authors
{
get { return this._authors; }
set { this._authors = value; }
}
private string _journal;
public string Journal
{
get { return this._journal; }
set { this._journal = value; }
}
private int _year;
public int Year
{
get { return this._year; }
set { this._year = value; }
}
public Article(string Title, string Authors, string Journal, int Year)
{
this._title = Title;
this._authors = Authors;
this._journal = Journal;
this._year = Year;
}
}
解决方案
你可以做这样的事情
var rows = GetDataGridRows(datagrid);
foreach (DataGridRow r in rows)
{
var rowHeight = r?.ActualHeight;
}
public IEnumerable<DataGridRow> GetDataGridRows(System.Windows.Controls.DataGrid grid)
{
var itemsSource = grid.ItemsSource as IEnumerable;
if (null == itemsSource) yield return null;
foreach (var item in itemsSource)
{
var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
if (null != row) yield return row;
}
}
Xaml
<StackPanel Orientation="Vertical" >
<Button Click="Button_Click" Height="39" Width="40"></Button>
<DataGrid x:Name="dgMain" AutoGenerateColumns="True" HorizontalAlignment="Left" Height="auto" VerticalAlignment="Top" Width="auto" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible" >
</DataGrid>
</StackPanel>
推荐阅读
- npm - 为什么 npm 会在我的项目根文件夹中安装一堆 .cmd 文件?
- visual-studio - 在项目选项中找不到跨平台应用程序 (Xamarin)
- javascript - div mouseenter() 或 hover()、delay()、fadeIn()、多个 div 条目在少于延迟时间 jQuery
- xcode - 无法在 Xcode 中构建:“代码对象在子组件中根本没有签名...... CocoaAsyncSocket.framework”
- spring - 构建 Spring 框架:为什么 IntelliJ 抱怨错误但编辑器似乎能够找到类?
- javascript - 跟踪复选框状态并为 ng-model 使用多个数据
- apache - mod_rewrite:由于可能的配置错误,请求超出了 10 个内部重定向的限制
- angular - Angular 2:未定义的路由参数值
- python - Square POS API - 可以从仪表板获取销售信息
- python - Python:你什么时候将变量放在函数内部或外部?