在我的 Maui xaml 中,我有一个最初启用的 Entry 控件,一旦用户在控件中输入了正确的值,我想以编程方式禁用它。
但事实并非如此
我的xaml代码看起来像这样
<Entry
x:Name="InputAnswer"
Margin="0,0,20,0"
FontSize="24"
HorizontalOptions="Start"
IsEnabled="{Binding IsWrong}"
Keyboard="Numeric"
MaxLength="5"
Placeholder=""
Text="{Binding InputAnswer}" />
我的模特班
public class EquationWithInput: Equation, INotifyPropertyChanged
{
public int? InputAnswer { get; set; }
public int CorrectAnswer{ get; set; }
public bool IsWrong { get => InputAnswer == null ? true : InputAnswer != CorrectAnswer; }
...
}
但是当我检查结果时,该控件从未被禁用。看起来绑定不起作用,但对于所有其他属性,该绑定在该页面的其他任何地方都有效。例如。
InputAnswer
。
那么我需要做什么才能让它发挥作用?
您需要确保 EquationWithInput 类正确实现 INotifyPropertyChanged 接口,并在 InputAnswer 更改时引发 PropertyChanged 事件,因为这会间接影响 IsWrong 属性。
以下是如何修改 EquationWithInput 类,以确保对 InputAnswer 的更改也正确通知 UI 有关 IsWrong 属性的更新:
public class EquationWithInput : Equation, INotifyPropertyChanged
{
private int? inputAnswer;
public int? InputAnswer
{
get { return inputAnswer; }
set
{
if (inputAnswer != value)
{
inputAnswer = value;
OnPropertyChanged(nameof(InputAnswer));
// Since IsWrong depends on InputAnswer, it needs to notify the change as well.
OnPropertyChanged(nameof(IsWrong));
}
}
}
public int CorrectAnswer { get; set; }
public bool IsWrong => InputAnswer == null || InputAnswer != CorrectAnswer;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}