从列表视图更改为数据网格后的验证错误
本文关键字:网格 验证 错误 数据网 数据 视图 列表 | 更新日期: 2023-09-27 18:32:08
我有一个验证良好的列表视图,但我想更改列表视图内部文本框的外观,所以我将其更改为 datagrid。我更改它后,验证被搞砸了。每当添加自动名称时,我都会收到错误消息,说该名称已经存在,即使它不存在。为什么列表视图没问题?欢迎任何意见。这是代码;
验证良好的列表视图:
<ListView Name="_regionQueryListBox" Width="122"
HorizontalAlignment="Left" VerticalAlignment="Stretch"
DataContext="{Binding}" IsSynchronizedWithCurrentItem="True"
Style="{StaticResource ListViewRegionSelectorStyle}"
ItemsSource="{Binding Path=Model}">
<ListView.View>
<GridView>
<GridViewColumn Header="Region"
Width="{Binding Path=ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListView}}">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox HorizontalAlignment="Left" VerticalAlignment="Stretch"
Text="{Binding Path=RegionName}">
</TextBox>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
数据网格,验证不起作用:
<DataGrid x:Name="_regionQueryListBox" HorizontalAlignment="Left" VerticalAlignment="Stretch"
AutoGenerateColumns="False"
AlternatingRowBackground="Silver" AlternationCount="2"
CanUserReorderColumns="False" CanUserResizeColumns="False" CanUserSortColumns="False"
CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeRows="False"
VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Disabled"
SelectionMode="Single"
DataContext="{Binding}"
ItemsSource="{Binding Path=Model}" >
<DataGrid.Columns>
<DataGridTemplateColumn Header="Region" Width="110" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=RegionName}"
TextChanged="regionTextBox_TextChanged" >
</TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
验证:
private void regionTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
{
TextBox textBox = sender as TextBox;
if (textBox != null)
{
string name = textBox.Text;
StringBuilder errorMessage = null;
RegionQueryViewModel queryViewModel = DataContext as RegionQueryViewModel;
if (queryViewModel.Model.Any(q => q.RegionName == name))
{
errorMessage = new StringBuilder();
errorMessage.AppendLine(string.Format("{0} already exists in the list.", name));
}
if (errorMessage != null)
{
MessageBox.Show(errorMessage.ToString(), "Item Already Exists");
name = string.Empty;
//RegionName = name;
return;
}
}
}
我猜数据网格的默认updatesourcetrigger=lostfocus会搞砸你的验证。
<DataTemplate>
<TextBox Text="{Binding Path=RegionName, UpdateSourceTrigger=PropertyChanged}"
TextChanged="regionTextBox_TextChanged" />
</DataTemplate>