WPF calculate Parent margin based on child control position
题
I have following XAML. I have to set margin to CanvasRuler
as per child control (LabelEditFrame
) Left position. How do I do that.
<wpfcommon:CanvasNavigationBar>
<DockPanel>
<wpfcommon:CanvasRuler /> <!-- Horizontal -->
</wpfcommon:CanvasRuler /> <!-- Vertical -->
<border>
<StackPanel>
<wpfcommon:LabelEditFrame>
</ wpfcommon:LabelEditFrame>
</StackPanel>
</border>
</DockPanel>
</wpfcommon:CanvasNavigationBar>
Right now I have this
I want to have this (I can do that by setting hard coded value, but I need to set it dynamically, so if position of child control gets changes, it will change ruler position automatically).
解决方案
From my experience, if this is on a Canvas and are children on a canvas, you can use the
Canvas.SetLeft
and
Canvas.SetTop
methods.
So for the Rulers, you can set the:
VerticalAlignment="Top", HorizontalAlignment="Left
Then when the LabelEditFrame is moved (whichever event you use to trigger that), you can adjust the two rulers with something like this:
Canvas.SetLeft(HorizontalCanvasRuler, LabelEditFrame.Margin.Left);
Canvas.SetTop(VerticalCanvasRuler, LabelEditFrame.Margin.Top);
I haven't tried this out, but I have used to adjust controls like this before so it should work :)
其他提示
I suggest you to put all that stuff to Grid and allow it calculate anything for you:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="SomeFixedHeightToGetTopMargin"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="SomeFixedWithToGetLeftMargin"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<wpfcommon:CanvasRuler Grid.Column="1"/>
<wpfcommon:CanvasRuler Grid.Row="1"/>
<Border Grid.Row="1" Grid.Column="1">
<StackPanel>
<wpfcommon:LabelEditFrame/>
</StackPanel>
</Border>
</Grid>