设置新行占位符的文本 [英] Setting text for new row placeholder

查看:76
本文介绍了设置新行占位符的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个启用了CanUserAddRows的简单数据网格:

I have a simple datagrid with CanUserAddRows enabled:

<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>

现在我想在新行中使用灰色的默认文本新行...占位符,当我单击它时会消失(添加新行)。

另一个问题我找到了以下设置前景色的方法:

Now I want to to have a gray default text "new row..." in the new row placeholder, which disappears, when I click on it (to add a new row).
In another question I found the following way to set the foreground color:

<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>

但是我也找不到一种添加文本的方法。

But I fail to find a way to add a text as well.

推荐答案

下面是我发现的解决方案的代码(使用帮助方法在可视化树中找到子级):

Here is a code behind solution I found (using a helper method to find children in the visual tree):

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可见并完全加载后进行以下调用:

Make the following call after the DataGrid became visible and is fully loaded:

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;

这篇关于设置新行占位符的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆