【问题标题】:Simplify using of ValidationRules简化 ValidationRules 的使用
【发布时间】:2017-05-06 20:13:07
【问题描述】:

我正在 WPF 中开发一个 C# 项目。

在我的主窗口中,我有 5 个(可能更晚)TextBox,每个框都包含一个 float,其值介于 0 和 100 之间。

我已经创建了一个验证规则:

class RangeValidationRule : ValidationRule
{
    public float MinValue { get; set; }
    public float MaxValue { get; set; }

    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        float intValue;

        string text = String.Format("Must be between {0} and {1}",
                       MinValue, MaxValue);
        if (!float.TryParse(value.ToString(), out intValue))
            return new ValidationResult(false, "Not a float");
        if (intValue < MinValue)
            return new ValidationResult(false, "To small. " + text);
        if (intValue > MaxValue)
            return new ValidationResult(false, "To large. " + text);
        return ValidationResult.ValidResult;
    }
}

但我不知道如何简化它的使用。其实我是这样用的:

<TextBox Grid.Row="3" Grid.Column="1"
         Style="{StaticResource StyleTextBox}">
    <TextBox.Text>
        <Binding Path="ValueToBind" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <local:RangeValidationRule MinValue="0" MaxValue="100"/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

如何简化我的代码?我可以为这种类型的 TextBox 创建样式吗?

<Style x:Key="StyleTextBox0To100" TargetType="TextBox"
       BasedOn="{StaticResource StyleTextBox}">
       <!-- What should I write ? -->
</Style>

【问题讨论】:

    标签: c# wpf validationrules


    【解决方案1】:

    您正在搜索的解决方案是BindingGroup

    以前问过question

    【讨论】:

    • 我尝试了两种方式来使用 BindingGroup(使用 Validation.ValidationAdornerSiteForBindingGroupName),但它对我不起作用。我可能错过了一些东西,但我不知道是什么
    猜你喜欢
    • 2011-12-14
    • 2011-06-21
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    相关资源
    最近更新 更多