簡體   English   中英

如何根據其內容而不是寬度等屬性觸發 WPF 網格上的 ValidationRule?

[英]How can I trigger a ValidationRule on a WPF grid based upon its contents, rather than its properties like width?

只能使用帶有綁定的ValidationRule 根據其內容而不是其屬性(如寬度等)將Validation.ErrorTemplateGrid一起使用的好方法是什么?

使用Tag屬性。

我的網格中有一組單選按鈕,我想確保至少有一個選中的成員。 如果沒有,我想用Validation.ErrorTemplate突出顯示整個網格,以提醒用戶他們沒有完成他們正在填寫的表單的一部分。

所以我在 XAML 中做了這個:

<Grid
    Name="GridReportType"
    Margin="0,20,0,0">
    <Grid.Tag>
        <Binding Path="ReportTypeSelected" 
            UpdateSourceTrigger="PropertyChanged" 
            Mode="OneWayToSource">
            <!--Validation rules only fire when target (WPF property) updates source (class property)-->
            <Binding.ValidationRules>
                <parent:FailIfFalse/>
            </Binding.ValidationRules>
        </Binding>
    </Grid.Tag>
</Grid

在構造函數后面的窗口代碼中使用這個:

this.GridReportType.Tag = false;

並使用此 ValidationRule:

public class FailIfFalse : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        if (!((bool)value))
        {
            return new ValidationResult(false, "Required");
        }
        else
        {
            return new ValidationResult(true, null);
        }
    }
}

並使用此錯誤模板:

<Grid.Style>
    <Style>
        <Style.Triggers>
        <Trigger Property="Validation.HasError" Value="True">
            <Setter Property="Validation.ErrorTemplate">
            <Setter.Value>
                <ControlTemplate>
                <DockPanel>
                    <TextBlock DockPanel.Dock="Bottom"
                       Foreground="Red"
                       FontSize="24"
                       FontStyle="Italic"
                       HorizontalAlignment="Center"
                       Text="{Binding ElementName=cantBeEmptyAdorner,
                        Path=AdornedElement.(Validation.Errors),
                        Converter={StaticResource GetLatestValidationError}}"/>
                    <Border BorderBrush="Red"
                        BorderThickness="1"
                        Margin="-1">
                    <AdornedElementPlaceholder x:Name="cantBeEmptyAdorner"/>
                    </Border>
                </DockPanel>
                </ControlTemplate>
            </Setter.Value>
            </Setter>
        </Trigger>
        </Style.Triggers>
    </Style>
</Grid.Style>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM