我有一个列表视图,验证很好,但我想改变listview里面的文本框的外观,所以我把它改成了datagrid。在我改变之后,验证被搞砸了。每当添加一个自动名称时,我收到错误消息,表明该名称已经存在,即使它不存在。为什么列表视图很好?欢迎任何输入。这是代码;
验证没问题的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;
}
}
}
答案 0 :(得分:0)
我猜测datagrid的默认updatesourcetrigger = lostfocus会影响您的验证。
<DataTemplate>
<TextBox Text="{Binding Path=RegionName, UpdateSourceTrigger=PropertyChanged}"
TextChanged="regionTextBox_TextChanged" />
</DataTemplate>