我一直在尋找這個問題近3天了。搜索還沒有出現。這些問題看起來像他們會回答我的問題,但結果是完全不同的東西。所以在這裏:在訪問視圖模型的數據網格中進行驗證?
我有一個視圖綁定到視圖模型。在視圖中,我有一個DataGrid,它由視圖模型中的列表填充。我們的標準是在字段以紅色突出顯示並且工具提示包含錯誤消息時進行數據錯誤驗證。從我讀過的在DataGrid中執行的操作中,我需要在屬性級別的類定義中執行驗證。
驗證正在查看輸入的值是否已存在於DataGrid中的項目列表中,這是View Model中的幫助。我無法弄清楚如何從我的類定義中獲得視圖模型的可尋址性。
我的資源字典中的定義:
<Style x:Key="DataGridTextBlockStyle" TargetType="{x:Type TextBlock}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
<Setter Property="ToolTipService.ShowDuration"
Value="20000"/>
</Trigger>
</Style.Triggers>
我的數據網格的定義:
<wpftk:DataGrid x:Name="SegmentGrid"
IsEnabled="True"
AutoGenerateColumns="False"
VerticalScrollBarVisibility="Auto"
Height="90"
ItemsSource="{Binding SegmentList}"
CanUserAddRows="False" CanUserDeleteRows="False" >
<event:EventCommandBehavior.EventCommands>
<event:EventCommand
RoutedEvent="wpftk:DataGrid.SelectionChanged"
Command="{Binding RegionSelectionChanged}"/>
</event:EventCommandBehavior.EventCommands>
<wpftk:DataGrid.Columns>
<wpftk:DataGridTextColumn Header="Name"
Width="265"
Binding="{Binding RegionName}" />
<!-- The Priority Column -->
<wpftk:DataGridTemplateColumn Header="Priority" Width="80">
<wpftk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Style="{StaticResource DataGridTextBlockStyle}"
Text="{Binding Priority, Mode=TwoWay,
ValidatesOnDataErrors=True,
ValidatesOnExceptions=True,
UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</wpftk:DataGridTemplateColumn.CellTemplate>
<wpftk:DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox>
<TextBox.Text>
<Binding Path="Priority"
UpdateSourceTrigger="PropertyChanged"
ValidatesOnDataErrors="True"
ValidatesOnExceptions="True">
</Binding>
</TextBox.Text>
<TextBox.Style>
<Style TargetType="TextBox" BasedOn="{StaticResource CellEditStyle}" />
</TextBox.Style>
</TextBox>
</DataTemplate>
</wpftk:DataGridTemplateColumn.CellEditingTemplate>
</wpftk:DataGridTemplateColumn>
<wpftk:DataGridCheckBoxColumn Header="Write To Cartridge"
Binding="{Binding WriteToCartridge, Mode=TwoWay}"/>
</wpftk:DataGrid.Columns>
</wpftk:DataGrid>
</StackPanel>
的優先領域是被確認的只有一個,但我有一個時間開溜得到它驗證。我發現的所有東西(在Priority setter中進行驗證,在自定義驗證器類中進行驗證)都會進行獨立驗證,無法訪問DataContext對象。
有沒有人知道一種方法來獲得訪問DataContext或指向我的類中的方法來進行驗證裏面呢?我嘗試在我的DataContext類中繼承IDataErrorInfo接口,但這並沒有被DataGrid單元調用。
你在哪裏試圖訪問DataContext?帶有Priority屬性的類應該實現IDataErrorInfo接口。請閱讀本文並相應地編輯您的問題:https://stackoverflow.com/help/mcve – mm8