计算DataTemplate生成元素的大小而不绘制它们

时间:2015-01-21 13:01:11

标签: c# wpf datatemplate itemscontrol

 public class Notifications: ObservableCollection < Notification > {}
 public Notifications Notifications = new Notifications();
 private readonly Queue < Notification > buffer = new Queue < Notification > ();

 public NotificationsWindows() {
    InitializeComponent();
    NotificationsControl.DataContext = Notifications;
    this.Height = SystemParameters.WorkArea.Height;
    this.Width = SystemParameters.WorkArea.Width / 3;
    this.Left = SystemParameters.WorkArea.Left + SystemParameters.WorkArea.Width - this.Width;
    this.Top = SystemParameters.WorkArea.Top;
 }

 public void AddNotification(Notification notification) {
    notification.Id = count++;

    if (NotificationsControl.ActualHeight + * what would be the size of the notification we want to add * > SystemParameters.WorkArea.Height) {
        buffer.Enqueue(notification);
    } else {
        if (corner == 0 || corner == 3) {
            Notifications.Insert(0, notification);
        } else {
            Notifications.Add(notification);
        }
    }

    //Show window if there're notifications
    if (Notifications.Count > 0 && !IsActive) Show();
 }

以下代码位于WPF窗口类中,NotificationsControl是一个项目控件,它通过«Notifications»集合应用数据模板。 我试图在屏幕上显示桌面警报,当使用所有屏幕的高度时会停止,所以我需要计算应用于数据模板时通知的大小。有可能吗?

1 个答案:

答案 0 :(得分:0)

感谢@Attila,它显示了搜索的位置。

如果control.DesiredSize超出Form&#39; s高度

,我会覆盖MeasureOverride将通知添加回缓冲区
        protected override Size MeasureOverride(Size finalSize)
    {
        Size ret = base.MeasureOverride(finalSize);
        Debug.WriteLine(NotificationsControl.DesiredSize);

        if (NotificationsControl.DesiredSize.Height >= Height && Notifications.Count > 0)
        {
            int index;
            if (corner == 0 || corner == 3)
            {
                index = 0;
            }
            else
            {
                index = Notifications.Count - 1;
            }
            buffer.Insert(0,Notifications[index]);
            Notifications.RemoveAt(index);
            InvalidateMeasure();
        }

        return ret;
    }

不确定是否需要InvalidateMeasure()