我有一个启用了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>
现在,我想在新行占位符中使用灰色的默认文本“新行...”,当我单击它时(添加新行),该文本将消失。
在另一个问题中,我找到了以下设置前景色的方法:
<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>
但是我也找不到一种添加文本的方法。
这是我找到的解决方案的代码(使用帮助程序方法在可视化树中找到子级):
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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句