這裏的問題是:WPF表單驗證當綁定值沒有改變
- 我有一個簡單的表格(文本框等)。
- 綁定全部在
BindingGroup
之內。 - 每個綁定都有
UpdateSourceTrigger=Explicit
集。 - 某些綁定具有附加的驗證規則,不允許使用空值/空值(必填字段)。
- 綁定全部在
- 我一個品牌綁定新,空對象的形式。
- 不輸入任何數據,用戶點擊保存按鈕觸發
BindingGroup.UpdateSources()
。 - UpdateSources成功,不會觸發驗證錯誤。
我相信這是因爲WPF只觸發每一個綁定的驗證規則,如果用戶已經積極地改變了用戶界面,字段的值,因爲我原來綁定一個空對象的形式,什麼都沒有改變。這不是我想要的行爲 - 我希望在調用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>
你可以發佈你的問題的示例示例。 – blindmeis