2013-01-18 81 views
2
爲DataGridRow

默認樣式行標題錯誤是如下:「」WPF的DataGrid,顯示伴隨工具提示

<Style x:Key="{x:Type DataGridRow}" TargetType="{x:Type DataGridRow}"> 
    <Setter Property="Background" Value="{DynamicResource {x:Static 
             SystemColors.WindowBrushKey}}" /> 
    <Setter Property="SnapsToDevicePixels" Value="true"/> 
    <Setter Property="Validation.ErrorTemplate" Value="{x:Null}" /> 
    <Setter Property="ValidationErrorTemplate"> 
    <Setter.Value> 
     <ControlTemplate> 
     <TextBlock Margin="2,0,0,0" VerticalAlignment="Center" 
            Foreground="Red" Text="!" /> 
     </ControlTemplate> 
    </Setter.Value> 
    </Setter> 
    <Setter Property="Template"> 
     ... 
    </Setter> 
</Style> 

我想要的是工具提示添加到TextBlock的,顯示在行標題中,它將從DataGridRow.Item.Error屬性(我的實體對象實現IDataErrorInfo)中收到錯誤消息。所以我做了以下幾點:

<TextBlock Margin="2,0,0,0" VerticalAlignment="Center" 
          Foreground="Red" Text="!" 
      ToolTip="{Binding RelativeSource={ 
          RelativeSource FindAncestor, 
          AncestorType={x:Type DataGridRow}}, 
          Path=Item.Error}"/> 

到目前爲止好。現在,錯誤屬性返回多行字符串,所以我想用TextBlock的工具提示:

<TextBlock Margin="2,0,0,0" VerticalAlignment="Center" 
          Foreground="Red" Text="!"> 
    <TextBlock.ToolTip > 
    <TextBlock Text="{Binding RelativeSource={ 
           RelativeSource FindAncestor, 
           AncestorType={x:Type DataGridRow}}, 
           Path=Item.Error}" 
       TextWrapping="Wrap"/> 
    </TextBlock.ToolTip> 
</TextBlock> 

但上面不會顯示錯誤消息;問題似乎是ToolTip不是父元素的可視化樹的一部分。我已閱讀PlacementTarget等,但仍無法完成工作。有人能告訴我正確的做法嗎?

回答

1

我認爲這個問題是綁定到(PlacementTarget),而不是元素本身給定元素的屬性相對源。但是RelativeSource標記擴展描述了綁定源相對於給定元素的位置。所以,我所做的就是 集PlacementTarget原始提示目標的祖先:

<Setter Property="ValidationErrorTemplate"> 
    <Setter.Value> 
    <ControlTemplate> 
     <TextBlock Margin="2,0,0,0" VerticalAlignment="Center" 
       HorizontalAlignment="Center" 
       TextAlignment="Center" 
       Foreground="Red" Text="!" 
       ToolTipService.PlacementTarget="{Binding RelativeSource={ 
           RelativeSource FindAncestor, 
           AncestorType={x:Type DataGridRow}}}"> 
     <TextBlock.ToolTip > 
      <ToolTip DataContext="{Binding Path=PlacementTarget, 
        RelativeSource={x:Static RelativeSource.Self}}"> 
      <TextBlock Text="{Binding Path=Item.Error}"/> 
      </ToolTip> 
     </TextBlock.ToolTip> 
     </TextBlock> 
    </ControlTemplate> 
    </Setter.Value> 
</Setter> 

現在的作品,因爲我想要的。

0

使用祖先水平在文字塊像下面

  <TextBlock Text="{Binding RelativeSource={ 
          RelativeSource FindAncestor, 
          AncestorType={x:Type DataGridRow},AncestorLevel=1}, 
          Path=Item.Error}" 
      TextWrapping="Wrap"/>