【问题标题】:compute size of DataTemplate-Generated Elements without drawing them计算 DataTemplate 生成元素的大小而不绘制它们
【发布时间】:2015-01-21 13:01:11
【问题描述】:
 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 » 集合上应用数据模板。 我试图在屏幕上显示桌面警报,当使用所有屏幕的高度时会停止,所以我需要计算应用到数据模板时通知的大小。有可能吗?

【问题讨论】:

  • 查看MSDN 页面中的测量和排列方法。如果在更新数据上下文后运行这些方法,则可以获得新的大小。如果它比您想要的大,请从数据上下文中删除通知。我曾经在标签大小上使用过这种方法,它也应该与其他 UIElement 一起使用。
  • @Attila 感谢我使用 MeasureOverride 让它工作了 :)

标签: c# wpf datatemplate itemscontrol


【解决方案1】:

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

如果 control.DesiredSize 超出表单的高度,我重写了 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 2013-04-20
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多