English 中文(简体)
WPF 装订值未更改时 WPF 窗体验证
原标题:WPF Form Validation When Binding Value Has Not Changed

问题在于:

  1. I have a simple form (textboxes, etc).
    • The bindings are all within a BindingGroup.
    • Each binding has UpdateSourceTrigger=Explicit set.
    • Some bindings have validation rules attached that do not allow blank/null values (required field).
  2. I bind a brand new, empty object to the form.
  3. Without entering any data, the user clicks the save button triggering BindingGroup.UpdateSources().
  4. UpdateSources succeeds, no validation errors are triggered.

我相信,这是因为 WPF 只有在用户积极改变UI中该字段的价值时, 才会触发每个约束性的验证规则, 而且由于我最初将一个空对象绑在窗体上, 没有任何变化。 这不是我想要的行为 - 我希望在调用“ 更新源代码” 时, 所有验证规则都得到评估 。

有没有人知道什么(希望干净的)方法 来得到我想要的行为?


以下是 C# 和 XAML 代码的一个( 简化的、 简化的) 示例 :

< 加固> 工具元元模板.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();

            // ...
        }
    }
}

< 坚固 > TOLTypeModelPanel.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>
最佳回答

My current workaround is: After binding a new item to the form, set fields of the form that need validation to a non-null but empty value for example:

this.modelNameTextBox.Text = string.Empty;

这导致 WPF 验证计划在源更新时验证此文本框的约束性。 如果有人有更干净的解决方案, 请告诉我 。

问题回答

为什么要设置更新源代码驱动器来为您明确控制? 将其更改为失去焦点或改变属性 。





相关问题
WPF convert 2d mouse click into 3d space

I have several geometry meshes in my Viewport3D, these have bounds of (w:1800, h:500, d:25). When a user clicks in the middle of the mesh, I want the Point3D of (900, 500, 25)... How can I achieve ...

Editing a xaml icons or images

Is it possible to edit a xaml icons or images in the expression design or using other tools? Is it possible to import a xaml images (that e.g you have exported) in the expression designer for editing?...

WPF: writing smoke tests using ViewModels

I am considering to write smoke tests for our WPF application. The question that I am faced is: should we use UI automation( or some other technology that creates a UI script), or is it good enough to ...

WPF - MVVM - NHibernate Validation

Im facing a bit of an issue when trying to validate a decimal property on domain object which is bound to a textbox on the view through the viewmodel. I am using NHibernate to decorate my property on ...

How do WPF Markup Extensions raise compile errors?

Certain markup extensions raise compile errors. For example StaticExtension (x:Static) raises a compile error if the referenced class cannot be found. Anyone know the mechanism for this? Is it baked ...

WPF design-time context menu

I am trying to create a custom wpf control, I m wondering how I can add some design-time features. I ve googled and can t seem to get to my goal. So here s my simple question, how can I add an entry ...

How to combine DataTrigger and EventTrigger?

NOTE I have asked the related question (with an accepted answer): How to combine DataTrigger and Trigger? I think I need to combine an EventTrigger and a DataTrigger to achieve what I m after: when ...

热门标签