2009-12-16 76 views
1

我想在DataGrid中的單元格上使用異常驗證以及DataGridTextColumn的EditingElementStyle樣式來設置帶有錯誤內容的工具提示。發生錯誤但未被捕獲或在WPF中顯示。WPF DataGrid驗證錯誤未被捕獲

代碼和例外如下所示。有人能告訴我我需要解決這個問題嗎?

乾杯,
Berryl

這裏的例外:

System.Windows.Data Error: 8 : Cannot save value from target back to source. 
BindingExpression:Path=Allocations[6].Amount; DataItem='ActivityViewModel' (HashCode=-938045583); 
target element is 'TextBox' (Name=''); 
target property is 'Text' (type 'String') 
TargetInvocationException:'System.Reflection.TargetInvocationException: 
Exception has been thrown by the target of an invocation. ---> 
Domain.Core.PreconditionException: An allocation must be less than one day. 

下面是DataGridTextColumn的XAML:

<dg:DataGridTextColumn 
    ....     
    EditingElementStyle="{StaticResource cellEditStyle}" 
    Binding="{Binding Allocations[6].Amount, Converter={StaticResource amtConv}, 
     ValidatesOnExceptions=True}" 
           /> 

這裏是應該提供工具提示反饋風格他錯誤:

<Style x:Key="cellEditStyle" TargetType="{x:Type TextBox}"> 
    <Setter Property="BorderThickness" Value="0"/> 
    <Setter Property="Padding" Value="0"/> 
    <Style.Triggers> 
     <Trigger Property="Validation.HasError" Value="true"> 
      <Setter 
       Property="ToolTip" 
       Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/> 
     </Trigger> 
    </Style.Triggers> 
</Style> 

回答

5

它可能有點晚,但由於我遇到了同樣的麻煩,這裏有一個解決方法以供進一步參考(使用.NET 4.0.30319進行測試)。

1)捕捉異常

而在原來的職位以下的綁定代碼工作正常與一個文本框,例如,它不與一個DataGrid文本單元(儘管MSN的文件指出如此):

<!-- Doesn't work --> 
<DataGridTextColumn Binding="{Binding Path=Age, ValidatesOnExceptions=True}" 
        ... 
        /> 

你必須添加此位:

<DataGridTextColumn Binding="{Binding Path=Age, Mode=TwoWay, ValidatesOnExceptions=True}" 
        ... 
        /> 

需要注意的是,奇怪的是(以我反正),這個異常將被捕獲並在行標題中顯示感嘆號。如果沒有Mode=TwoWay部分,您將不會擁有紅色邊框,也無法應用樣式。

2)應用樣式

另一個困難是設置一個樣式錯誤的情況下,因爲當你開始驗證過程中,編輯元素將立即關閉。因此附上一個樣式:

<!-- Doesn't work --> 
<DataGridTextColumn Binding="{Binding Path=Age, Mode=TwoWay, ValidatesOnExceptions=True}" 
        EditingElementStyle="{StaticResource datagridTBStyle}" 
        ... 
        /> 

如果您想觸發驗證錯誤,將無法正常工作。同樣的,CellStyle不會觸發錯誤標誌。你必須使用一個技巧和聲明FrameworkElement的風格,像這樣:

<DataGridTextColumn Binding="{Binding Path=Age, Mode=TwoWay, ValidatesOnExceptions=True}" 
        ElementStyle="{StaticResource datagridElemStyle}" 
        ... 
        /> 

好消息是,你可以從它們的屬性定義樣式派生的元素,像一個TextBlock,並從中受益:

<Style x:Key="datagridElemStyle" TargetType="{x:Type TextBlock}"> 
    <Style.Triggers> 
    <Trigger Property="Validation.HasError" Value="True"> 
     <Setter Property="Background" Value="Yellow" /> 
     <Setter Property="ToolTip" 
       Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/> 
    </Trigger> 
    </Style.Triggers> 
</Style>