为新行占位符设置文本
本文关键字:置文本 占位符 新行 | 更新日期: 2023-09-27 18:12:06
我有一个简单的数据网格启用CanUserAddRows:
<DataGrid Name="TestCasesDataGrid" Padding="0 0 5 0" AutoGenerateColumns="False" CanUserAddRows="True" CanUserDeleteRows="True" CanUserSortColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Width="100" Binding="{Binding Name}" />
</DataGrid.Columns>
</DataGrid>
现在我想在新行占位符中有一个灰色的默认文本"new row…",当我点击它(添加新行)时,它会消失。
在另一个问题中,我发现了以下设置前景色的方法:
<DataGrid Name="TestCasesDataGrid" Padding="0 0 5 0" AutoGenerateColumns="False" CanUserAddRows="True" CanUserDeleteRows="True" CanUserSortColumns="False">
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<DataTrigger Binding="{Binding}" Value="{x:Static CollectionView.NewItemPlaceholder}">
<Setter Property="Foreground" Value="Gray" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Width="100" Binding="{Binding Name}" />
</DataGrid.Columns>
</DataGrid>
但是我没有找到一个方法来添加一个文本
下面是我找到的解决方案背后的代码(使用helper方法在可视化树中查找子节点):
public static DependencyObject FindChild(DependencyObject parent, Func<DependencyObject, bool> predicate)
{
if (parent == null) return null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (predicate(child))
{
return child;
}
else
{
var foundChild = FindChild(child, predicate);
if (foundChild != null)
return foundChild;
}
}
return null;
}
在DataGrid变为可见并且完全加载后,执行以下调用:
var dataGridRow = Tools.FindChild(testCasesDataGrid, x =>
{
var element = x as DataGridRow;
if (element != null && element.Item == System.Windows.Data.CollectionView.NewItemPlaceholder)
return true;
else
return false;
}) as DataGridRow;
var textBlock = Tools.FindChild(dataGridRow, x =>
{
return x is TextBlock;
}) as TextBlock;
textBlock.Text = "new row...";
textBlock.Foreground = System.Windows.Media.Brushes.Gray;
你试过了吗?
<DataGrid Name="TestCasesDataGrid" Padding="0 0 5 0" AutoGenerateColumns="False" CanUserAddRows="True" CanUserDeleteRows="True" CanUserSortColumns="False">
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<DataTrigger Binding="{Binding}" Value="{x:Static CollectionView.NewItemPlaceholder}">
<Setter Property="Foreground" Value="Gray" />
<Setter Property="TextBlock.Text" Value="New Row" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Width="100" Binding="{Binding Name}" />
</DataGrid.Columns>
</DataGrid>