MVVM 中的可见性转换器未更新

Visibility converter in MVVM not updating

我想根据某些 TextBoxes 的值是否大于其他 TextBoxes 的值来更改 Grid 的可见性。我正在使用 MVVM 并具有以下代码:

XAML

<UserControl.Resources>
    <BooleanToVisibilityConverter x:Key="BoolToVis"/>
</UserControl.Resources>

<Grid x:Name="TimeError" Visibility="{Binding Path=IsTimeValid, Converter={StaticResource BoolToVis}}">
    <TextBlock Text="Incorrect value"/>
</Grid>

<TextBox x:Name="TotalStarthh" MaxLength="2" FontSize="16" Width="28" Text="{Binding TotalStarthh}"/>
<more TextBoxes/>

在 ViewModel 中,我将 textBoxes 解析为整数值并计算总时间。

private string _TotalStarthh;
public string TotalStarthh
{
    get { return _TotalStarthh; }
    set { _TotalStarthh = value; NotifyPropertyChanged(); }
}
//The same for the other TextBoxes.

public int Totalstart()
{
    int.TryParse(TotalStarthh, out int TShh);
    int.TryParse(TotalStartmm, out int TSmm);
    int.TryParse(TotalStartss, out int TSss);
    //calculating hours:mins:sec to total seconds
    //This can be over 24 hours so datetime is not used
    int Totalstart = TShh * 3600 + TSmm * 60 + TSss;
    return Totalstart;
}

public int Totalend()
{
    int.TryParse(TotalEndhh, out int TEhh);
    int.TryParse(TotalEndmm, out int TEmm);
    int.TryParse(TotalEndss, out int TEss);
    //calculating hours:mins:sec to total seconds
    //This can be over 24 hours so datetime is not used
    int Totalend = TEhh * 3600 + TEmm * 60 + TEss;
    return Totalend;
}

// validate that start time is lower than end time.
public bool IsTimeValid
{
    get { return (Totalstart > Totalend); }
    set { NotifyPropertyChanged(); }
}

但这不会更新 Grid 的可见性。我做错了 NotifyPropertyChanged 吗?我是 mvvm 的新手,我仍在努力掌握它。提前致谢。

您的 TotalStarthh属性 发生了变化。您的 UI 会收到通知。但是您从未通知 UI IsTimeValid 可能也已更改。

您可以将 IsTimeValid 设为普通 属性,并在每次从属 属性 更改时将其设置为您想要的布尔值。

或者您可以在每次更改使用的两个属性时通知 UI IsTimeValid 已更改。要解释具体方法,我们需要知道您的 NotifyPropertyChanged 实际长什么样。

如果我不得不猜测,我会说这可能会成功:

public string TotalStarthh
{
    get { return _TotalStarthh; }
    set 
    {
         _TotalStarthh = value;
         NotifyPropertyChanged(); // notifies the UI this property has changed
         NotifyPropertyChanged("IsTimeValid"); // notifies the UI IsTimeValid has changed 
    }
}

您需要在通知前实际将 属性 设置为新值。 为此,请使用带有支持字段的 属性。

private bool isTimeValid;
public bool IsTimeValid
{ 
  get { return (Totalstart > Totalend); }
  set
  {
    if(value != isTimeValid)
      {
        isTimeValid = value;
        NotifyPropertyChanged(nameof(IsTimeValid));
      }
   }
 }

强烈建议使用 Prism MVVM 框架。它有一个 SetProperty 函数,可以在一行中为您完成所有这些工作。