I have a window which is its size can be change during run time by user.
I want to draw a horizontal line which extends to the width of window.
I can do this by code behind (on window resize event, change the size of line),
but am looking for a way to change the size of line in xaml, so for example bind x1,x2,y1 and y2 to their parents (or window) size in a way that line resize itself when the size of window changes.
How can I do this?
In this case, the maybe try use Separator
:
A
Separator
control draws a line, horizontal or vertical, between items in controls, such as ListBox, Menu, and ToolBar.
For Separator base class is Control
, this means that it is possible to apply a Style/ControlTemplate, that is comfortable when you want stored separately properties for him.
Example:
<Grid>
<Separator Name="MySeparator"
Height="4"
Width="Auto"
HorizontalAlignment="Stretch"
VerticalAlignment="Bottom"
Background="Black" />
</Grid>
This example draws a line in bottom on the entire Width of the Window
. Setting properties Width="Auto"
and HorizontalAlignment="Stretch"
can automatically stretch Separator at the Width of the Window.
To specify an arbitrary Height
for Separator, use the following style:
<Style TargetType="{x:Type Separator}">
<Setter Property="OverridesDefaultStyle" Value="True" />
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Separator}">
<Rectangle SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
Height="{TemplateBinding Height}"
Width="{TemplateBinding Width}"
Fill="{TemplateBinding Background}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
This draws a line the width of the Window, regardless of which Panel
you choose. (Canvas, Grid, StackPanel
, etc.).
It also works if you need a line that is not parallel to the Window top.
// Assumes the Window is named MainWindow
XAML
<Canvas>
<Line X1='0'
X2='{Binding ActualWidth, Mode=OneWay,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type local:MainWindow}}}'
Y1='50'
Y2='90'
Stroke="Orange"
StrokeThickness='2' />
<Line X1='0'
X2='{Binding ActualWidth, Mode=OneWay,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type local:MainWindow}}}'
Y1='110'
Y2='110'
Stroke="Green"
StrokeThickness='2' />
</Canvas>
Screenshots
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With