开发者

WPF programmatically setting fields as required

开发者 https://www.devze.com 2023-04-10 18:46 出处:网络
I am fairly new to WPF but have spent time researching WPF validation, and have not yet seen a good approach to conditional validation.

I am fairly new to WPF but have spent time researching WPF validation, and have not yet seen a good approach to conditional validation.

To simplify the situation greatly, l开发者_如何学运维et's say I have two textboxes and a submit button. The user enters a string in the first textbox. If the user enters, for example "ABC", then the second textbox should be a required field (I'd want the background to be a light blue color, to signify this), and the submit button should be disabled until that textbox is populated.

How can this be done? Is there an easy way to add/remove validations in runtime? 'DataAnnotations' (http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx) seemed like a good starting place, however I can't mark a field with the [Required] attribute, as the field won't always be required. Basically, I need something like 'Required if Field1 = 'ABC'

Thanks!


I would handle it using MVVM and here is a sample for that. Implement IDataError Info on the class and that will implement two properties Error and this[string columnName] you can implement the second property with your binding errors that you want

public class MainViewModel:ViewModelBase,IDataErrorInfo  
{

 public string Error
  {
  }
public string this[string columnName]

{
 get
  {
     string msg=nulll;
     switch(columnName)
        {
          case "MyProperty": //that will be your binding property
           //choose your validation logic
           if(MyProperty==0||MyProperty==null)
             msg="My Property is required";
            break;
         }
     return msg;
    }
}

Also Set ValidateOnErrors=True in binding of a textbox. here ColumnName is the name of the property that is changed and that has ValidateOnErrors set to true. Check here and put up the conditions and return message then you will see the errors on the tooltip when you put this style in your Resources.

<UserControl.Resources>
    <Style TargetType="{x:Type TextBox}">
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="true" >
                <Setter Property="Foreground" Value="Red"/>
                <Setter Property="Background" Value="MistyRose"/>
                <Setter Property="BorderBrush" Value="Red"/>
                <Setter Property="BorderThickness" Value="1.0"/>
                <Setter Property="VerticalContentAlignment" Value="Center"/>
                <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</UserControl.Resources>

and here is a sample of the textbox

<TextBox Text="{Binding UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, 
 Path=PropertyName,ValidatesOnDataErrors=True}" Name="textBox1">
  <Validation.ErrorTemplate>
        <ControlTemplate>
          </ControlTemplate>
   </Validation.ErrorTemplate>

 </TextBox>


I would just handle this logic in your ViewModel (assuming you're using an MVVM pattern, if not just in your code-behind).

Fire some logic on the TextChanged event for the first textbox that ultimately sets the appropriate properties. Essentially I'm saying code this validation manually. Once you start getting into more complex validation logic like this your going to start running into the limitations of the validation frameworks / declarative validation.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号