3

我有一个带有 Canvas 的 ItemsPanelTemplate 的 ListBox。我知道除非给定高度和宽度,否则 ScrollViewer 将无法与 Canvas 一起使用。我不想给画布一个高度和宽度,因为它并不总是恒定的。是否有任何其他解决方法或技巧有人已经为这种情况工作。我知道我不能是唯一遇到这个问题的人。提前谢谢这里是我到目前为止的代码。

另一个问题是我无法将 ScrollViewer 放在 ItemsPanelTemplate 中,因为它只能嵌套一个元素。

这也限制了我将画布放在网格内以获得定位。

XAML:

    <!--Core Viewer-->
    <ScrollViewer x:Name="scrollViewer"
                  VerticalScrollBarVisibility="Hidden"
                  HorizontalScrollBarVisibility="Hidden">

        <ListBox x:Name="objCoreViewer"
             ItemsSource="{Binding ItemsSource}"
             Background="LightGray"
             SelectionChanged="objCoreViewer_SelectionChanged"
             ItemTemplateSelector="{DynamicResource CoreViewerDataTemplateSelector}"
             ItemContainerStyleSelector="{DynamicResource ItemContainerStyleSelector}"
             PreviewMouseWheel="objCoreViewer_PreviewMouseWheel">

            <!-- Core Map Canvas -->

            <ListBox.ItemsPanel>

                <ItemsPanelTemplate>
                    <Canvas x:Name="objCoreViewerCanvas"
                            Background="Transparent">
                        <Canvas.LayoutTransform>
                            <ScaleTransform ScaleX="{Binding Path=Value, ElementName=ZoomSlider}"
                                            ScaleY="{Binding Path=Value, ElementName=ZoomSlider}" />
                        </Canvas.LayoutTransform>
                    </Canvas>
                </ItemsPanelTemplate>

            </ListBox.ItemsPanel>

        </ListBox>

    </ScrollViewer>
4

1 回答 1

2

要使画布根据其中的子元素增长,您需要在继承自 Canavas 的自定义类中覆盖 Canvas 的 MeasureOverride 事件。这段代码对我很有用:

 protected override System.Windows.Size MeasureOverride(System.Windows.Size constraint)
    {
        Size toReport = new Size();

        foreach (UIElement element in this.InternalChildren)
        {
            //Get the left most and top most point.  No using Bottom or Right in case the controls actual bottom and right most points are less then the desired height/width
            var left = Canvas.GetLeft(element);
            var top = Canvas.GetTop(element);

            left = double.IsNaN(left) ? 0 : left;
            top = double.IsNaN(top) ? 0 : top;

            element.Measure(constraint);

            Size desiredSize = element.DesiredSize;

            if (!double.IsNaN(desiredSize.Width) && !double.IsNaN(desiredSize.Height))
            {
                //left += desiredSize.Width;
                //top += desiredSize.Height;

                toReport.Width = toReport.Width > left +desiredSize.Width ? toReport.Width : left + desiredSize.Width;
                toReport.Height = toReport.Height > top+desiredSize.Height ? toReport.Height : top + desiredSize.Height;
            }

        }

        //Make sure scroll includes the margins incase of a border or something
        toReport.Width += this.Margin.Right;
        toReport.Height += this.Margin.Bottom;

        return toReport;
    }
于 2011-06-09T12:32:31.490 回答