I would like to create elements during runtime and add a style to them.
Given the following Xaml, I would like to bind the value for the property Center
to the actual values of a styled object (see main method). I tried different Binding notations but without success (propably because I am still new to xaml). I also tried to just change the Center
on the instance but the instance is frozen and cannot be changed.
<Window x:Name="window" x:Class="CirclePing.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style x:Key="AlertBubble" TargetType="{x:Type Path}">
<Setter Property="StrokeThickness" Value="0"/>
<Setter Property="Data">
<Setter.Value>
<!-- how can I bind Center to the Tag property of a 'styled' instance? -->
<EllipseGeometry x:Name="circle"
Center="200,200"
RadiusX="100"
RadiusY="100">
</EllipseGeometry>
</Setter.Value>
</Setter>
<Setter Property="Fill">
<Setter.Value>
<RadialGradientBrush>
<GradientStop Color="Black"/>
<GradientStop Color="#2F5CB2"/>
</RadialGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="OpacityMask">
<Setter.Value>
<RadialGradientBrush>
<GradientStop Color="#00000000" Offset="0.5"/>
<GradientStop Color="#FFFFFFFF" Offset="1"/>
</RadialGradientBrush>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
</Window>
My Main
method:
InitializeComponent();
Random r = new Random();
for (int i = 0; i < 500; i++)
{
var path = new Path();
int positionX = r.Next(1400);
int positionY = r.Next(800);
path.Tag = new Point(positionX, positionY);
path.Style = (Style)this.Resources["AlertBubble"];
}
Now I would like the following to be true: (EllipseGeometry)path.Data).Center.Y == positionY
. What binding expression should I use?
You can bind Center using RelativeSource
markup extension and finding parent Path instance object like this:
<EllipseGeometry x:Name="circle"
Center="{Binding Tag, RelativeSource={RelativeSource
Mode=FindAncestor, AncestorType=Path}}"
RadiusX="100"
RadiusY="100"/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.