C# 验证WPF时禁用按钮
我对一个属性进行了规则验证。我想要的是,当条件不满足时,保存按钮应该被禁用。我怎么做?这就是它的样子: . 按钮未被禁用 这是我的密码C# 验证WPF时禁用按钮,c#,.net,wpf,validation,mvvm,C#,.net,Wpf,Validation,Mvvm,我对一个属性进行了规则验证。我想要的是,当条件不满足时,保存按钮应该被禁用。我怎么做?这就是它的样子: . 按钮未被禁用 这是我的密码 公共字符串字段名{get;set;} public Regex regularpression=new Regex(“^[a-zA-Z]*$”; 公共覆盖验证结果验证(对象值,CultureInfo CultureInfo) { //var stringValue=作为字符串的值; 如果(字段名=“年龄”) 返回值(值); 如果(字段名=“名称”) 返回名称验证
公共字符串字段名{get;set;}
public Regex regularpression=new Regex(“^[a-zA-Z]*$”;
公共覆盖验证结果验证(对象值,CultureInfo CultureInfo)
{
//var stringValue=作为字符串的值;
如果(字段名=“年龄”)
返回值(值);
如果(字段名=“名称”)
返回名称验证(值);
返回新的ValidationResult(true,null);
}
私有验证结果名称验证(对象值)
{
var onlyCharacters=regularExpression.IsMatch((字符串)值);
如果(仅限字符)
返回新的ValidationResult(true,null);
其他的
返回新的ValidationResult(false,仅限字母字符“$”);
}
在XAML中:
<Label Grid.Row="0" Grid.Column="0" Margin="103,0,98,10" Content="Name : " VerticalContentAlignment="Center" HorizontalContentAlignment="Right" Grid.ColumnSpan="2"/>
<TextBox Grid.Row="0" Grid.Column="1" x:Name="txtCourtName" Margin="113,4,-55,6" VerticalContentAlignment="Center" HorizontalContentAlignment="Left" Validation.ErrorTemplate="{StaticResource errorTemplate}" >
<TextBox.Text>
<Binding Path="CourtName" ValidatesOnDataErrors="true" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local11:AuthValidation FieldName="Name"></local11:AuthValidation>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
按钮:
<Button Content="Save" x:Name="btnSaveCourt" Command="{Binding SaveCourt}" Margin="2,10" Width="119" Background="#909090" Foreground="Black" BorderBrush="White" />
和我的错误模板:
<ControlTemplate x:Key="errorTemplate">
<Border BorderBrush="OrangeRed" BorderThickness="2">
<Grid>
<AdornedElementPlaceholder>
<TextBlock Text="{Binding [0].ErrorContent}" Foreground="OrangeRed"
VerticalAlignment="Center" HorizontalAlignment="Right"
Margin="-220"
>
</TextBlock>
</AdornedElementPlaceholder>
</Grid>
</Border>
</ControlTemplate>
您可以将按钮的IsEnabled绑定到一个属性,一个bool propfull(write propfull选项卡,它将在visual studio中为您写出它) 或者可以在按钮上使用MultiDataTrigger并绑定要验证的文本框的所有HasError属性
或者,如果使用命令,则可以使用命令的can execute属性。而不是使用
验证规则,当您想禁用按钮
时,应该实现SaveCourt
命令的CanExecute
方法返回false
。可能有用:永远不要尝试设置按钮。i在MVVM中启用-最好使用带有CanExecute机制的ICommand实现。通常最好使用CanExecute但并不总是理想的。有时,您可能有不涉及用户输入或大量命令的逻辑。在这种情况下,您会发现InvalidateRequestSuggested有问题。@Peregrine也可以在xaml中的操作中使用它。它没有在MVVM中设置IsEnabled,而是从xaml绑定到它,以防代码中也有一些逻辑。