2013-01-31 69 views
6

妖異的this問題 -WPF驗證ErrorTemplate自定義文本框

當安裝驗證錯誤模板,我的自定義文本框這樣的 -

<local:CustomTextBox CustomText="{Binding ViewModelProperty}" Validation.ErrorTemplate="{StaticResource errorTemplate}"/> 

<ControlTemplate x:Key="errorTemplate"> 
    <DockPanel> 
     <Border BorderBrush="Red" BorderThickness="1"> 
      <AdornedElementPlaceholder x:Name="controlWithError"/> 
     </Border> 
     <TextBlock Foreground="Red" FontSize="20" FontFamily="Segoe UI" Margin="3,0,0,0" MouseDown="Exclamation_MouseDown" Tag="{Binding AdornedElement.(Validation.Errors)[0].ErrorContent, ElementName=controlWithError}">!</TextBlock> 
    </DockPanel> 
</ControlTemplate> 

如果有在ViewModelProperty驗證錯誤,我應用程序拋出異常 -

Key cannot be null. 
Parameter name: key 

我不知道爲什麼會發生這種情況。是否需要完成某些操作才能將新的錯誤模板分配給自定義控件?

UPDATE:

我已經想通了,這個問題是在錯誤模板標籤屬性。如果我刪除標籤,它工作得很好。

感謝

回答

4

好了,所以我設法解決這個問題的方式是通過除去AdornedElement關鍵字和改變錯誤模板如下:

<local:CustomTextBox CustomText="{Binding ViewModelProperty}"> 
    <Validation.ErrorTemplate> 
     <ControlTemplate> 
      <DockPanel> 
       <Border BorderBrush="Red" BorderThickness="1"> 
        <AdornedElementPlaceholder x:Name="controlWithError"/> 
       </Border> 
       <TextBlock Foreground="Red" FontSize="20" FontFamily="Segoe UI" Margin="3,0,0,0" MouseDown="Exclamation_MouseDown">!</TextBlock> 
      </DockPanel> 
     </ControlTemplate> 
    </Validation.ErrorTemplate> 
    <local:CustomTextBox.Style> 
     <Style TargetType="{x:Type local:CustomTextBox}"> 
      <Style.Triggers> 
       <Trigger Property="Validation.HasError" Value="true"> 
        <Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}"/> 
        <Setter Property="Tag" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}"/> 
       </Trigger> 
      </Style.Triggers> 
     </Style> 
    </local:CustomTextBox.Style> 
</local:CustomTextBox> 

我不明白的是爲什麼它的表現在使用AdornedElement關鍵字時不同,但在使用RelativeSource綁定標籤/工具提示時工作正常。問題解決後,我會歡迎任何想法,爲什麼發生這種情況。

感謝

+3

我意識到這是一個老問題,但我猜,你的第一個例子中拋出一個異常,因爲有在'Validation.Errors'集合中沒有錯誤,但你試圖綁定到第一個(不存在的)錯誤的'ErrorContent'屬性。在你的解決方案中,當HasError屬性爲true時,你只能選擇綁定到錯誤消息,因此當集合中有一個或多個錯誤時。即使在第二個示例中,您仍應該看到在Visual Studio的「輸出」窗口中顯示的「異常」。 – Sheridan