【发布时间】:2012-06-01 00:40:26
【问题描述】:
问题来了:
- 我有一个简单的表单(文本框等)。
- 绑定都在
BindingGroup中。 - 每个绑定都设置了
UpdateSourceTrigger=Explicit。 - 某些绑定附加了不允许空白/空值(必填字段)的验证规则。
- 绑定都在
- 我将一个全新的新、空对象绑定到表单。
- 没有输入任何数据,用户点击保存按钮触发
BindingGroup.UpdateSources()。 - UpdateSources 成功,没有触发验证错误。
我相信这是因为 WPF 仅在用户主动更改 UI 中该字段的值时才会触发每个绑定的验证规则,并且由于我最初将空对象绑定到表单,因此没有任何更改。这不是我想要的行为 - 我希望在调用 UpdateSources 时评估所有验证规则。
有没有人知道一种(希望是干净的)方法来获得我想要的行为?
以下是 C# 和 XAML 代码的(缩短的、简化的)示例:
ToolTypeModelPanel.xaml.cs
private void addModelButton_Click(object sender, RoutedEventArgs e)
{
ToolModel model = new ToolModel();
// bind the model details view to the new model
this.createModelBinding = new Binding();
this.createModelBinding.Source = model;
this.modelFormGrid.SetBinding(Grid.DataContextProperty, this.createModelBinding);
}
private void saveModelButton_Click(object sender, RoutedEventArgs e)
{
Binding modelDataContext = this.modelFormGrid.GetBindingExpression(Grid.DataContextProperty).ParentBinding;
if (modelDataContext == this.modelDetailsBinding && this.modelListBox.SelectedItem != null)
{
// update existing tool model
if (this.modelFormBindingGroup.UpdateSources())
{
// ...
}
}
else if (modelDataContext == this.createModelBinding)
{
// create new tool model
ToolModel modelToCreate = (ToolModel)this.createModelBinding.Source;
if (this.modelFormBindingGroup.UpdateSources())
{
Context.ToolModel.AddObject(modelToCreate);
Context.SaveChanges();
// ...
}
}
}
ToolTypeModelPanel.xaml
<GroupBox
Grid.Row="3"
Grid.Column="2"
Margin="5"
Header="{x:Static prop:Resources.HeaderModelDetails}">
<Grid x:Name="modelFormGrid" DataContext="{Binding ElementName=modelListBox, Path=SelectedItem}">
<Grid.BindingGroup>
<BindingGroup x:Name="modelFormBindingGroup" />
</Grid.BindingGroup>
<Label Grid.Row="0" Grid.Column="0" Content="{x:Static prop:Resources.LabelModelName}" />
<TextBox x:Name="modelNameTextBox"
Grid.Row="0"
Grid.Column="1">
<TextBox.Text>
<Binding Path="ModelName" UpdateSourceTrigger="Explicit">
<Binding.ValidationRules>
<vr:RequiredValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<Label Grid.Row="3" Grid.Column="0" Content="{x:Static prop:Resources.LabelModelParameter}" />
<TextBox x:Name="modelParameterTextBox"
Grid.Row="3"
Grid.Column="1"
Text="{Binding Path=ModelParameter, UpdateSourceTrigger=Explicit}" />
<Label Grid.Row="4" Grid.Column="0" Content="{x:Static prop:Resources.LabelFactoryAssemblyName}" />
<TextBox x:Name="modelFactoryAssemblyTextBox"
Grid.Row="4"
Grid.Column="1">
<TextBox.Text>
<Binding Path="FactoryAssemblyName" UpdateSourceTrigger="Explicit">
<Binding.ValidationRules>
<vr:NamespaceValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<Button x:Name="saveModelButton"
Width="100"
Margin="36,0,0,0"
IsEnabled="False"
Content="{x:Static prop:Resources.ButtonSaveText}"
Click="saveModelButton_Click" />
</Grid>
</GroupBox>
【问题讨论】:
-
您能否针对您的问题发布一个示例示例。
标签: wpf data-binding validation