这是我所拥有的......显示的是 ListView 的一部分。当前发生的情况是:用户单击“新建”按钮以创建新行。在单击“保存”按钮之前,用户可能会也可能不会在包含的文本框/组合框中输入信息。单击 Save 按钮时,将执行下面的 C# 代码,该代码使用 VisualTreeHelper 查找 ListView 中的所有 TextBoxes/ComboBoxes,并确保用户已输入文本/选择了一个项目。如果他们没有,它会将 BorderBrush 设置为红色并阻止 ObjectContext 保存更改。我知道在某些情况下您可以使用 ValidationRule ......但我无法弄清楚如何让它验证在单击“保存”按钮之前从未选择/更改过的新行。这可行,但很好奇是否有更优雅的方式。
XAML
<ListView.View>
<GridView>
<GridViewColumn x:Name="nameColumn" Header="Name" Width="100">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox Margin="-6,-1" >
<TextBox.Text>
<Binding Path="Name" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<me:TextInputValidator />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
C#
Stack<FrameworkElement> tree = new Stack<FrameworkElement>();
tree.Push(subcategoryListView);
while (tree.Count > 0)
{
FrameworkElement current = tree.Pop();
int count = VisualTreeHelper.GetChildrenCount(current);
for (int i = 0; i < count; ++i)
{
DependencyObject child = VisualTreeHelper.GetChild(current, i);
if (child is FrameworkElement)
tree.Push((FrameworkElement)child);
if (child is TextBox)
{
TextBox tempBox = child as TextBox;
if (string.IsNullOrEmpty(tempBox.Text))
{
tempBox.BorderBrush = new SolidColorBrush(Colors.Red);
errorsOnPage = true;
}
}
if (child is ComboBox)
{
ComboBox tempCombo = child as ComboBox;
if (tempCombo.SelectedIndex == -1)
{
tempCombo.BorderBrush = new SolidColorBrush(Colors.Red);
errorsOnPage = true;
}
}
}
}
if (!errorsOnPage)
{
dbcontext.SaveChanges();
MessageBox.Show("Saved", null, MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
MessageBox.Show("Highlighted fields are missing or invalid.", null, MessageBoxButton.OK, MessageBoxImage.Stop);
}
}
catch (Exception ex)
{
MessageBox.Show("Error encountered while saving", null, MessageBoxButton.OK, MessageBoxImage.Stop);
}