-1

检查某个容器或其子容器是否存在验证错误非常容易。这可以用来禁用Save按钮。

我可以使用计时器

public SomeUserControl()
{
    InitializeComponent();
    var timer = new DispatcherTimer
    {
        Interval = TimeSpan.FromMilliseconds(100),
        IsEnabled = true
    };
    Loaded += (s, e) => buttonSave.IsEnabled = IsValid(grid);
    Unloaded += (s, e) => timer.Stop();
}

轮询和禁用按钮。

<!-- container with lots of controls, bindings and validations -->
<Grid x:Name="grid">
   ...
</Grid>

<!-- save button -->
<Button x:Name="buttonSave" ... />

有没有更好的办法?理想情况下,我想要一个活动。不幸的是,我发现的唯一事件 Validation.Error事件只能用于具有绑定本身的元素。通过子元素和订阅(更不用说我必须处理添加新子元素)感觉比投票更糟糕。

想法?

4

1 回答 1

1

我通常处理此问题的方式如下所示:

https://social.technet.microsoft.com/wiki/contents/articles/28597.aspx

错误事件将冒泡到容器中,您可以处理它,使用行为或命令将其传递给视图模型。

像:

<ControlTemplate x:Key="AddingTriggers" TargetType="ContentControl">
    <ControlTemplate.Resources>
        <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource ErrorToolTip}">
            <Setter Property="HorizontalAlignment" Value="Left"/>
        </Style>

    </ControlTemplate.Resources>
    <StackPanel>
        <i:Interaction.Triggers>
            <local:RoutedEventTrigger RoutedEvent="{x:Static Validation.ErrorEvent}">
                <e2c:EventToCommand   Command="{Binding ConversionErrorCommand, Mode=OneWay}"
                                        EventArgsConverter="{StaticResource BindingErrorEventArgsConverter}"
                                        PassEventArgsToCommand="True" />
            </local:RoutedEventTrigger>
        </i:Interaction.Triggers>
        <TextBlock Text="This would be some sort of a common header" Foreground="LightBlue" HorizontalAlignment="Right"/>
        <ContentPresenter/> <!-- This is how you can have variable content "within" the control -->
        <TextBlock Text="This would some sort of a common footer" Foreground="LightBlue"  HorizontalAlignment="Right"/>
    </StackPanel>
</ControlTemplate>

您需要 NotifyOnValidationError=True 在任何绑定上。

于 2019-10-17T12:07:49.010 回答