This project has moved and is read-only. For the latest updates, please go here.

Validation for ProperyGrid Property

Dec 9, 2015 at 2:37 PM
How to set Validation for Property ?

Is it possible Property Grid ?

For Example, I want to set the int property should have integer value greater than 100 ?
Developer
Dec 11, 2015 at 6:46 PM
Hi,

you can use PropertyGrid.EditorDefinitions to define a DataTemplate for property of type "Integer" and then use the Binding.ValidationRules.
<Window.Resources>
      <Style x:Key="ControlInError"
             TargetType="xctk:PropertyGridEditorIntegerUpDown">
         <Style.Triggers>
            <Trigger Property="Validation.HasError"
                     Value="true">
               <Setter Property="ToolTip"
                       Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors).CurrentItem.ErrorContent}" />
            </Trigger>
         </Style.Triggers>
      </Style>
   </Window.Resources>
    <Grid>
      <xctk:PropertyGrid x:Name="_propertyGrid">
         <xctk:PropertyGrid.EditorDefinitions>
            <xctk:EditorTemplateDefinition TargetProperties="{x:Type sys:Int32}">
               <xctk:EditorTemplateDefinition.EditingTemplate>
                  <DataTemplate>
                     <xctk:PropertyGridEditorIntegerUpDown TextAlignment="Left"
                                                           Style="{StaticResource ControlInError}">
                        <xctk:PropertyGridEditorIntegerUpDown.Value>
                           <Binding Path="Value"
                                    UpdateSourceTrigger="PropertyChanged">
                              <Binding.ValidationRules>
                                 <local:IntegerValidationRule />
                              </Binding.ValidationRules>
                           </Binding>
                        </xctk:PropertyGridEditorIntegerUpDown.Value>
                     </xctk:PropertyGridEditorIntegerUpDown>
                  </DataTemplate>
               </xctk:EditorTemplateDefinition.EditingTemplate>
            </xctk:EditorTemplateDefinition>
         </xctk:PropertyGrid.EditorDefinitions>
      </xctk:PropertyGrid>
   </Grid>
public class IntegerValidationRule : ValidationRule
  {
    public override ValidationResult Validate( object value, CultureInfo cultureInfo )
    {
      int intValue;
      bool success = int.TryParse( value.ToString(), out intValue );
      if( success && (intValue < 100) )
        return new ValidationResult( true, null );

      return new ValidationResult( false, "Please enter a valid integer value." );
    }
  }