2010-07-15 32 views
0

如何對DataGridTemplateColumn使用單元格和行驗證?WPF DataGrid - 如何使用DataGridTemplateColumn對單元格和行進行驗證

<DataGridTemplateColumn.CellTemplate> 
    <DataTemplate> 
     <TextBlock Text="{Binding DataType}"/> 
    </DataTemplate> 
</DataGridTemplateColumn.CellTemplate> 
<DataGridTemplateColumn.CellEditingTemplate> 
    <DataTemplate> 
     <ComboBox SelectedItem="{Binding DataType}" ItemsSource="{Binding Source={x:Static app:ApplicationConfiguration.DataTypes}, ValidatesOnDataErrors=True}"/> 
    </DataTemplate> 
</DataGridTemplateColumn.CellEditingTemplate> 
+0

一些更多的背景下...你到底想做什麼?例如使用WPF驗證模型(請參閱IDataErrorInfo)+數據綁定,您可以將驗證移動到ViewModel類。網格可以保持幸福無知。 – Gishu 2010-07-15 06:33:15

+0

我的模型實現了IDataErrorInfo,所以我只想觸發單元格和行級別驗證。 – 2010-07-15 06:50:19

+0

多一點背景。對於文本列,一切都很好。但是對於模板或組合框列,當值更改時,無法更新行級驗證。 – 2010-07-15 06:52:10

回答

1

這是一個猜測,但它看起來像你想阻止某些項目被選中。最簡單的方法是將它們從列表中刪除,但是您可以使用以下驗證方法進行操作。

如果所選項目是無效的,拋出一個異常,在視圖模型的二傳手:

public object DataType 
{ 
    get { return dataType; } 
    set 
    { 
     if(valueNotAllowed(value)) 
      throw new Exception(string.Format("{0} is not a valid selection", value.ToString()); 
     dataType = value; 
    } 
} 

然後設置的SelectedItem綁定到ValidateOnExceptions(注意,在你的問題,你指定ValidatesOnErrors的ItemsSource結合 - 錯誤性質的錯誤綁定):

<ComboBox SelectedItem="{Binding Path=DataType, ValidatesOnExceptions=True}" 
ItemsSource="{Binding Source={x:Static app:ApplicationConfiguration.DataTypes}}"/> 
相關問題