首页 > 解决方案 > WPF - 如何将元素设置为逐行标记,而不是行索引

问题描述

我正在寻找一种方法来执行该SetRow(UIElement element, int value)方法,但不是使用 int 值来放置元素,而是使用行的标记来查找特定行。

基本上是这样的:

 RowDefinition newRow = new RowDefinition();
 newRow.Tag = "This is the row I want to find";
 TextBlock newBlock = new TextBlock();
 Grid.SetRow(newBlock, "This is the row I want to find");

然后它会根据标签找到该行并将文本块放在那里。是否有一种预先存在的方法可以做到这一点,或者是否有人对如何为其制作自定义方法有任何想法?

标签: c#wpfrow

解决方案


如果newRownewBlock已经被添加到同一个网格中,你可以这样做

var rowTag = "This is the row I want to find";

if (newBlock.Parent is Grid grid)
{
    var row = grid.RowDefinitions.FirstOrDefault(r => rowTag.Equals(r.Tag));

    if (row != null)
    {
        Grid.SetRow(newBlock, grid.RowDefinitions.IndexOf(row));
    }
}

推荐阅读