简体   繁体   English

WPF画布具有相对位置

[英]WPF canvas with relative position

I have this DataGrid and this Canvas : 我有这个DataGrid和这个Canvas

<DataGrid Canvas.ZIndex="1" x:Name="dgTimeline"/>

<Canvas Height="30" Width="999" Canvas.ZIndex="2" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="71,387,0,0">
    <Line Name="time" X1="0" Y1="0" X2="0" Y2="24" Stroke="Black" StrokeThickness="2"/>
</Canvas>

Which results in: 结果是: 在此处输入图片说明

However, when I move the horizontal scroll bar of the DataGrid the Canvas obviously stays on its position because its parent is the Window and not the DataGrid : 但是,当我移动DataGrid的水平滚动条时, Canvas显然会停留在其位置,因为其父级是Window而不是DataGrid 在此处输入图片说明

Is it possible to keep Canvas ' position relative to the DataGrid instead of its parent in such a way that when scrolling the DataGrid the Canvas would stay stationary as it was a DataGrid 's element? 是否可以通过以下方式保持Canvas相对于DataGrid而不是其父级的位置,即在滚动DataGrid Canvas会保持静止,因为它是DataGrid的元素? I tried to put the Canvas inside of the DataGrid but that didn't work. 我试图将Canvas放入DataGrid内,但这没有用。

You can add horizontal scrollbar to canvas and then try to synchronize the horizontal scrolls of canvas and datagrid. 您可以将水平滚动条添加到画布,然后尝试同步画布和数据网格的水平滚动。 something like ... 就像是 ...

private void dataGrid_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
    canvasScrollViewer.ScrollToHorizontalOffset(e.HorizontalOffset);
}

private void canvasScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
    ScrollViewer dgScrollViewer = GetScrollViewerInstance();
    dgScrollViewer.ScrollToHorizontalOffset(e.HorizontalOffset);
}

private ScrollViewer GetScrollViewerInstance()
{
    var ctrl = VisualTreeHelper.GetChild(dataGrid, 0);
    if (ctrl is Border)
    {
        var ctrl1 = VisualTreeHelper.GetChild(ctrl, 0);
        if (ctrl1 is ScrollViewer)
        {
            dgScrollViewer = ctrl1 as ScrollViewer;
        }
    }
}

This code is just to give you an idea of how to do it and not a actual working code. 这段代码只是为了让您了解如何执行此操作,而不是实际的工作代码。 You set the HorizontalScrollBarVisibility for Canvas to Hidden if you don't want to show it. 如果不想显示画布,可以将“画布”的Horizo​​ntalScrollBarVisibility设置为“隐藏”。 You will not need the second event handler in that case. 在这种情况下,您将不需要第二个事件处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM