wpf ValicationRule 和 BindingGroup
1.自定义一个ValicationRule:
public class RangeValidationRule:ValidationRule { public override ValidationResult Validate(object value, CultureInfo cultureInfo) { double myValue = 0; if(double.TryParse(value.ToString(),out myValue)) { if (myValue >= 0 && myValue <= 100) { return new ValidationResult(true, null); } } return new ValidationResult(false, "Input should between 0 and 100"); } }
使用:
<Grid> <Slider Margin="10,120,-10,-120" Minimum="0" Maximum="100" Name="slider" Value="10"></Slider> <TextBox Height="50" Margin="5,30,5,240" > <TextBox.Text> <Binding ElementName="slider" Path="Value" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <local:RangeValidationRule/> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> </Grid>
2.BindingGroup的使用
public class MyClass { public int StartValue { get; set; } public int EndValue { get; set; } }
public class RangeValidationRule : ValidationRule { public override ValidationResult Validate(object value, CultureInfo cultureInfo) { BindingGroup bindingGroup = (BindingGroup)value; MyClass mc = (MyClass)bindingGroup.Items[0]; int startValue = (int)bindingGroup.GetValue(mc, "StartValue"); int endValue = (int)bindingGroup.GetValue(mc, "EndValue"); bool isEnabled = (bool)bindingGroup.GetValue(mc, "IsEnabled"); if (startValue > endValue) { return new ValidationResult(true, null); } return new ValidationResult(false, "Input should between 0 and 100"); } }
MyClass mc = new MyClass(); public MainWindow() { InitializeComponent(); this.DataContext = mc; }
<Grid Name="Grid1" Width="400" Height="300" > <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Grid.BindingGroup> <BindingGroup NotifyOnValidationError="True"> <BindingGroup.ValidationRules > <local:RangeValidationRule2 ValidationStep="ConvertedProposedValue" /> </BindingGroup.ValidationRules> </BindingGroup> </Grid.BindingGroup> <TextBox Grid.Row="0" Name="tb1" Text="{Binding StartValue}"> </TextBox> <TextBox Grid.Row="1" Text="{Binding EndValue}"/> <Button Name="btn1" Content="btn1" Grid.Row="2" Click="Button_Click" > </Button> </Grid>
验证:
this.Grid1.BindingGroup.CommitEdit();