WPF验证取决于必需/不需要字段

时间:2015-10-21 09:49:33

标签: c# wpf validation xaml

我是WPF新手的新手,但我在考虑如何一举三得。 示例:我有一个包含2个TextBox和2个TextBlocks的表单。 第一个'鸟'是能够用一个星号“丰富”一些文本块,如果它们引用必填字段:

<TextBlock Grid.Row="0" Grid.Column="0" Text="Age" customProperty="Required" /> <TextBlock Grid.Row="1" Grid.Column="0" Text="Foot Size/>

然后TextBlocks将以不同的方式显示其文本,第一个将带有星号,而没有定义任何customproperty的那个将没有。

第二只鸟将对文本框的值进行某种验证,如果我理解正确是通过使用CustomValidationRule完成的,我实现了一个类:

class AgeController: ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        if (value == null)
            return new ValidationResult(false, "Null value");

        int temp = 1;
        Boolean noIllegalChars = int.TryParse(value.ToString(), out temp);
        if (temp >= 1)
            return new ValidationResult(true, null);
        else
            return new ValidationResult(false, "Correggi");
    }
}

将其添加到textBlox XAML代码中:

<TextBox.Text>
     <Binding Path="blabla" UpdateSourceTrigger="PropertyChanged"  ValidatesOnDataErrors="True">
         <Binding.ValidationRules>
              <local:AgeController ValidationStep="RawProposedValue" />
         </Binding.ValidationRules>
     </Binding>
</TextBox.Text>

这样可行但是验证过程应该是必需的而不是必需的字段:如果需要空白输入无效,但如果它是可选的,则空白字段是可以的。 如何在引用链接到文本框的文本块时指定两个不同的ValidationRule来实现此目的?

/ tldr:我正在尝试找到一种方法来丰富文本块,该文本块具有为其文本添加样式的属性(星号或客户想要的任何内容,我修改了浓缩在一个地方修改文本的方式),然后,根据丰富的价值,文本框对丰富文本块的验证会有不同的行为。

我希望我没有搞砸这个解释。

4 个答案:

答案 0 :(得分:9)

<强> 1。 TextBlock没有ControlTemplate属性。因此,所需的(*)无法添加到TextBlock

Label有一个controltemplate,可以将焦点放在输入字段上。我们来使用吧。

在按下Alt + F时,使用目标属性将焦点传递给TextBox:

<!-- Prefixing Firstname with _ allows the user to give focus
     to the textbox (Target) by pressing Alt + F-->

    <local:LabelWithRequiredInfo  Content="_Firstname" 
                                  IsRequired="false" 
                                  Target="{Binding ElementName=textboxFirstname,
                                  Mode=OneWay}" ... />

创建Label的子类:LabelWithRequiredInfo,因此可以添加IsRequired属性。
(使用VS添加新项目/ WPF自定义控件)。

<强> 2。为控件创建IsRequired依赖属性,因此绑定将起作用 - 我们需要它!

public class LabelWithRequiredInfo : Label
{
    public bool IsRequired
    {
        get { return (bool)GetValue(IsRequiredProperty); }
        set { SetValue(IsRequiredProperty, value); }
    }

    // Using a DependencyProperty as the backing store for IsRequired.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty IsRequiredProperty =
        DependencyProperty.Register("IsRequired", typeof(bool), typeof(LabelWithRequiredInfo), new PropertyMetadata(false));
    static LabelWithRequiredInfo()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(LabelWithRequiredInfo), new FrameworkPropertyMetadata(typeof(LabelWithRequiredInfo)));
    }
}

第3。让我们填充Themes \ Generic.xaml中的LabelWithRequiredInfo模板

(但模板首先在MainWindow.xaml rigth中设计,点击标签/编辑模板/复制 - 这样它可以显示 - 然后模板内容被复制到Generic.xaml中)

<Style TargetType="{x:Type local:LabelWithRequiredInfo}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:LabelWithRequiredInfo}">
                <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
                    <!-- A grid has been added to the template content to have multiple content.  -->
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="30"/>
                        </Grid.ColumnDefinitions>
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        <!-- The Visibility  property has to be converted because it's not a bool but has a Visibility type
                             The converter (pretty classical) can be found in the attached solution, and is declared in the resource section
                             The binding is made on a property of the component : IsRequired
                        -->
                        <TextBlock  Text="(*)" 
                                    Visibility="{TemplateBinding IsRequired,Converter={StaticResource booleanToVisibilityConverter}}"
                                    Foreground="Red"
                                    Grid.Column="1"
                                    Margin="5 0"/>
                    </Grid>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsEnabled" Value="false">
                        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                    </Trigger>
                </ControlTemplate.Triggers>

            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<强> 4。 Generic.xaml中的转换器声明:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:TextboxRequiredMandatoryInput">
    <local:BooleanToVisibilityConverter  x:Key="booleanToVisibilityConverter"/>

<强> 5。考虑IsRequired行为的ValidationRule声明:

class RequiredValidationRule : ValidationRule
{
    public bool IsRequired { get; set; }
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        var content = value as String;
        if (content != null)
        {
            if (IsRequired && String.IsNullOrWhiteSpace(content))
                return new ValidationResult(false, "Required content");
        }
        return ValidationResult.ValidResult;
    }
}

<强> 6。并在您的绑定中使用它:

<TextBox x:Name="textboxFirstname" HorizontalAlignment="Left" Height="23" Margin="236,94,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120">
    <TextBox.Text>
        <Binding Path="Firstname" UpdateSourceTrigger="PropertyChanged"  ValidatesOnDataErrors="True">
            <Binding.ValidationRules>
                <local:RequiredValidationRule IsRequired="true" ValidationStep="RawProposedValue" />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

您将在此处找到完整的解决方案:

http://1drv.ms/1igpsyb

答案 1 :(得分:4)

对于可重用性和描述要求的方式,可能需要聚合控制。我认为UserControl +一些DependencyProperty是完美的。

对于我的UserControl,我会喜欢这个..

<UserControl x:Class="WpfApplication1.InputFieldControl"
         x:Name="InputUserCtrl"
         ...             >
<StackPanel x:Name="MainPanel">
    <TextBlock x:Name="Label">
        <TextBlock.Text>
            <MultiBinding StringFormat="{}{0}{1}:">
                <Binding Path="InputLabel" ElementName="InputUserCtrl"/>
                <Binding Path="RequiredStringSymbol" ElementName="InputUserCtrl"/>
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>
    <TextBox x:Name="Value" Text="{Binding DataContext, ElementName=InputUserCtrl}"/>
</StackPanel>

然后在它的部分类(我添加了多个属性,请参阅用法部分):

public partial class InputFieldControl : UserControl
{
    // Required property
    public static readonly DependencyProperty RequiredProperty =
                   DependencyProperty.Register("Required", 
                   typeof(bool), typeof(InputFieldControl), 
                   new PropertyMetadata(true, OnRequiredChanged));
    private static void OnRequiredChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){
        InputFieldControl ctrl = d as InputFieldControl;
        // symbol is voided
        if ((bool)e.NewValue == false)
            ctrl.RequiredStringSymbol = string.Empty;
    }
    public bool Required {
        get { return (bool)GetValue(RequiredProperty); }
        set { SetValue(RequiredProperty, value); }
    }
    // Required string symbol
    public static readonly DependencyProperty RequiredStringSymbolProperty =
                  DependencyProperty.Register("RequiredStringSymbol",
                  typeof(string), typeof(InputFieldControl),
                  new PropertyMetadata("*"));
    public string RequiredStringSymbol{
        get { return (string)GetValue(RequiredStringSymbolProperty); }
        set { SetValue(RequiredStringSymbolProperty, value); }
    }
    // Input Label
    public static readonly DependencyProperty InputLabelProperty =
                  DependencyProperty.Register("InputLabel",
                  typeof(string), typeof(InputFieldControl),
                  new PropertyMetadata(string.Empty));
    public string InputLabel{
        get { return (string)GetValue(InputLabelProperty); }
        set { SetValue(InputLabelProperty, value); }
    }

我可以像这样使用控件:

<StackPanel>
    <customCtrl:InputFieldControl Required="True"
                                  RequiredStringSymbol="+" 
                                  InputLabel="RequiredField"/>
    <customCtrl:InputFieldControl Required="False"
                                  InputLabel="NormalField"/>
    <customCtrl:InputFieldControl Required="True"
                                  RequiredStringSymbol="*" 
                                  InputLabel="AnotherRequiredField">
    </customCtrl:InputFieldControl>
</StackPanel>

关于验证部分,我宁愿使用IDataErrorInfo。这可以与您的ViewModel一起使用,因为我们现在可以绑定Required属性。

答案 2 :(得分:3)

第一点:您可以为控件定义自定义模板,您可以在其中添加所需的可视元素(星号等)。您可以使用触发器控制其可见性。 (你可以问一个单独的问题,了解更多细节)

秒/第三:您可以在IsRequired上定义布尔属性AgeController,并在定义验证时将其设置为TRUE / FALSE:

<TextBox.Text>
     <Binding Path="blabla" UpdateSourceTrigger="PropertyChanged"  ValidatesOnDataErrors="True">
         <Binding.ValidationRules>
              <local:AgeController ValidationStep="RawProposedValue" 
                                                   IsRequired="**True**" />
                                               OR: IsRequired="**False**" />

         </Binding.ValidationRules>
     </Binding>
</TextBox.Text>

然后,在实施验证时,您可以使用此值:

public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        if (IsRequired)
        {
           ...
        }
        else
        {
           ...
        }
    }

答案 3 :(得分:0)

这是第二个答案,不完全是马西莫的问题。

我做到了,认为它可以更容易用于XAML设计师

目标是让Label(子类实际上具有所需的红色符号(*))更容易使用。

由于通常的目标属性

为TexBlock提供了重点
<local:LabelWithRequiredInfo  Content="_Firstname" 
                              Target="{Binding ElementName=textboxFirstname, Mode=OneWay}" 
                              ... />  

由于存在目标, LabelWithRequiredInfo 可以检查 TextBox.TextProperty 中是否存在 RequiredValidationRule

所以大部分时间都不需要IsRequired属性。

public LabelWithRequiredInfo()
{
    var dpd = DependencyPropertyDescriptor.FromProperty(Label.TargetProperty, typeof(Label));
    dpd.AddValueChanged(this, SearchForRequiredValidationRule);
}
private void SearchForRequiredValidationRule(object sender, EventArgs e)
{
    var textbox = Target as TextBox;
    if (textbox != null)
    {
        Binding binding = BindingOperations.GetBinding(textbox, TextBox.TextProperty);
        var requiredValidationRule = binding.ValidationRules
                                            .OfType<RequiredValidationRule>()
                                            .FirstOrDefault();
        if (requiredValidationRule != null)
        {
            // makes the required legend (red (*) for instance) to appear
            IsRequired = true;
        }
    }
}

如果必须在复选框或组合框上提供必需的图例,或者 LabelWithRequiredInfo

上仍有 IsRequired 属性
<local:LabelWithRequiredInfo  Content="_I agree with the terms of contract" 
                              Target="{Binding ElementName=checkboxIAgree}"
                              IsRequired='"true"                                  
                              ... />

仍然可以在文本框(或任何控件)上添加其他验证规则来检查数字,正则表达式,...

最后一个奖励,将 RequiredLegend 设置为 LabelWithRequiredInfo 中的依赖项属性:

public Object RequiredLegend
{
    get { return (Object)GetValue(RequiredLegendProperty); }
    set { SetValue(RequiredLegendProperty, value); }
}

// Using a DependencyProperty as the backing store for RequiredLegend.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty RequiredLegendProperty =
    DependencyProperty.Register("RequiredLegend", typeof(Object), typeof(LabelWithRequiredInfo), new PropertyMetadata(null));

这样 LabelWithRequiredInfo 的模板可以用它来显示一些文字:

<local:LabelWithRequiredInfo RequiredLegend="(*)" ... />

或更多XAML-ish:

<local:LabelWithRequiredInfo ... >
    <local:LabelWithRequiredInfo.RequiredLegend>
        <TextBlock Text="(*)" Foreground="Red" />
    </local:LabelWithRequiredInfo.RequiredLegend>

只需更改 themes \ Generic.xaml 中的控件模板即可。

它现在使用ContentControl来显示文本或控件:

<Style TargetType="{x:Type local:LabelWithRequiredInfo}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:LabelWithRequiredInfo}">
                <Border ...>
                    <Grid>
                        <Grid.ColumnDefinitions ... />
                        <ContentPresenter ... />
                        **<ContentControl Content="{TemplateBinding RequiredLegend}" Visibility="{TemplateBinding IsRequired,Converter={StaticResource booleanToVisibilityConverter}}" Grid.Column="1" /> **
                    </Grid>

以下是完整解决方案的链接:before_action

最佳编码