我尝试使用DataGrid
来启用用户输入新记录。
ItemsSource
绑定到ObservableCollection<MyObject>
。
MyObject
已实施IDataErrorInfo
进行验证,INotifyPropertyChanged
将PropertyChanged
通知给用户界面。
问题:
我如何克服以下问题?
问题:
在编辑模式下,当我在单元格中键入长错误字符串时,它会在TextBox
周围显示错误指示符(红色边框),但是当离开单元格时,指示符将超出以覆盖其他列像这样:
XAML:
<DataGrid VerticalAlignment="Top" Margin="0,5" CanUserAddRows="True" AutoGenerateColumns="False" ItemsSource="{Binding Pricelist}" >
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Validation.ErrorTemplate" Value="{x:Null}"/>
</Style>
</DataGrid.CellStyle>
<DataGrid.Columns>
<DataGridTextColumn Header="Price" Width="60" >
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="Text" Value="{Binding Price, Mode=TwoWay}"/>
</Style>
</DataGridTextColumn.ElementStyle>
<DataGridTextColumn.EditingElementStyle>
<Style TargetType="TextBox">
<Setter Property="Text" Value="{Binding Price, ValidatesOnDataErrors=True}"/>
</Style>
</DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
注意:
我认为所有这些都非常典型,而且应该是直截了当的,但我的经验是DataGrid
非常繁琐。以下是我所做的让我解决这个问题的步骤:
删除this problem的ValidationErrorTemplate
。
分别明确定义ElementStyle
和EditingElementStyle
,并在Mode=TwoWay
ElementStyle
设置ValidatesOnDataErrors=True
。
从ElementStyle
删除了MultiDataTrigger
,以允许用户在当前单元格中出现错误时能够编辑任何其他单元格。
如果单元格的值为BorderBrush
,则定义Red
将Null
设置为ItemsControl
以显示空单元格的错误指示符。
我可能会使用DataGrid
,但我确实喜欢{{1}}的一些内置功能。