代码之家  ›  专栏  ›  技术社区  ›  jason.kaisersmith

无法通过绑定禁用条目

  •  0
  • jason.kaisersmith  · 技术社区  · 2 年前

    在我的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 .

    那么,我需要做些什么才能让它发挥作用呢?

    2 回复  |  直到 2 年前
        1
  •  1
  •   Nikos Basdanis    2 年前

    您需要确保 带输入的等式 类正确地实现了INotifyPropertyChanged接口,并引发 属性已更改 事件时 InputAnswer 更改,因为这会间接影响 我错了 所有物

    以下是如何修改 带输入的等式 类,以确保更改为 InputAnswer 正确地通知UI有关的更新 我错了 属性:

    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));
        }
    
    }
    
    
        2
  •  0
  •   Hossam Fares    2 年前

    问题是您必须调用 PropertyChanged 事件时 IsWrong 属性已设置,但在您的情况下(即 我错了 属性取决于其他属性),您可以调用 属性已更改 的事件 InputAnswer 属性setter和name参数应该是IsWrong属性的名称,例如

    public string InputAnswer
    {
      set 
      {
          //other logic 
     
        OnPrepertyChanged(nameof(IsWrong));
      }
      //other logic
    }