【发布时间】:2021-07-29 20:06:41
【问题描述】:
情况:
当您点击新产品时,会弹出一个屏幕:
您可以看到“Opslagen”按钮被禁用,这很好,因为“Productnaam”是强制性的。
现在,如果我开始键入“Opslagen”按钮已启用,到目前为止还可以。
但是当我删除 tekst 时,一条红色消息显示此字段是必填字段,但该按钮将不再禁用:
当我再次输入内容时,红色文字再次消失。但按钮行为未按预期工作。
XAML:
<TextBox Width="200"
Height="30"
HorizontalAlignment="Left"
VerticalContentAlignment="Center">
<TextBox.Text>
<Binding Path="ProductName" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<validators:EmptyValidationRule ValidatesOnTargetUpdated="True" ValidationStep="RawProposedValue" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
<Validation.ErrorTemplate>
<ControlTemplate>
<StackPanel>
<!-- Placeholder for the TextBox itself -->
<AdornedElementPlaceholder x:Name="textBox"/>
<TextBlock Text="{Binding [0].ErrorContent}" Foreground="Red"/>
</StackPanel>
</ControlTemplate>
</Validation.ErrorTemplate>
</TextBox>
EmptyValidationRule 类:
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (value == null)
{
return new ValidationResult(true, null);
}
if (!string.IsNullOrEmpty(value.ToString()) && !string.IsNullOrWhiteSpace(value.ToString()))
{
return new ValidationResult(true, null);
}
return new ValidationResult(false, "Dit veld is verplicht.");
}
最后是 ViewModel 中的 IsSaveButtonDisabled 属性:
public bool IsSaveButtonEnabled
{
get
{
if (!string.IsNullOrEmpty(_productName) && !string.IsNullOrWhiteSpace(_productName))
{
return true;
}
else
{
return false;
}
}
}
我真的不知道。它必须是 ValidationRule 和检查属性 ProductName 是否为空的组合。
编辑,按钮代码:
<Button Content="Opslagen"
IsEnabled="{Binding IsSaveButtonEnabled}"
Background="Bisque"
Width="120"
Height="30"
Command="{Binding SaveCommand}" />
产品名称属性:
private string _productName;
public string ProductName
{
get => _productName;
set
{
_productName = value;
RaisePropertyChanged(nameof(ProductName));
RaisePropertyChanged(nameof(IsSaveButtonEnabled));
}
}
保存命令是这样的:
SaveCommand = new RelayCommand(SaveProduct);
而SaveProduct只是一种保存产品的方法。这东西有效。
【问题讨论】:
-
Button如何启用或禁用?您是在使用命令还是如何禁用它? -
@mm8 按钮具有属性 IsEnabled="{Binding IsSaveButtonEnabled}"
-
@DzianisKarpuk 这不是问题。
-
@user7849697 你的按钮的实现在哪里?你说,这个问题出在你的按钮上,但只给出了文本框的实现。
-
@DzianisKarpuk 更新了按钮代码。
标签: c# xaml mvvm validationrule