我最近创建了一个用户控件,通知用户他有多少通知。因为我希望这个用户控件仅在有任何通知时才显示自己,所以我创建了一个绑定到布尔值的 DataTrigger,并在没有通知时将可见性设置为折叠。它在开始时工作正常,我的用户控件已折叠,但在我的程序中,我添加了一个通知并在我的 bool 上调用 NotifyPropertyChanged,但用户控件由于某种未知原因仍然保持隐藏状态。
用户控制
<UserControl.Style>
<Style TargetType="{x:Type UserControl}">
<Setter Property="Visibility"
Value="Visible">
</Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding HasNotifications}"
Value="False">
<Setter Property="Visibility"
Value="Collapsed">
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</UserControl.Style>
数据上下文
private ObservableCollection<Notification> notifications;
public ObservableCollection<Notification> Notifications
{
get { return notifications; }
}
public bool HasNotifications
{
get
{
return Notifications.Count > 0;
}
}
public void AddNotification(Notification notificationToAdd)
{
notifications.Add(notificationToAdd);
NotifyPropertyChanged(nameof(Notifications));
NotifyPropertyChanged(nameof(HasNotifications));
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
我还尝试放置一个具有相反值的 DataTrigger(当 HasNotifications 为 true 时将可见性设置为 on),但它对我也不起作用。