我有一个验证良好的列表视图,但我想更改列表视图内部的文本框的外观,所以我将其更改为数据网格。在我改变它之后,验证搞砸了。每当添加自动名称时,我都会收到错误消息,指出该名称已存在,即使它不存在。为什么列表视图很好?欢迎任何意见。这是代码;
验证良好的Listview:
<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,验证不起作用:
<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;
}
}
}