2015-09-09 49 views
0

設置文本我有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> 

現在我想有一個灰色的默認文本「新行......」 ,當我點擊它(添加一個新行)。
another question我發現下面的方法來設置前景色:

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

但我無法找到一個方法來添加一個文本爲好。

回答

1

這裏是後面的解決方案代碼,我發現(使用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; 
-1

你試過這個嗎?

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

我做了,它不起作用。 –