我想在运行时创建元素并为其添加样式。
给定以下Xaml,我想将属性的值绑定Center
到样式对象的实际值(请参阅main方法)。我尝试了不同的Binding表示法,但是没有成功(可能是因为我对xaml还是陌生的)。我也尝试只更改Center
实例上的实例,但是实例被冻结,无法更改。
<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>
我的Main
方法:
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"];
}
现在,我希望做到以下几点:(EllipseGeometry)path.Data).Center.Y == positionY
。我应该使用什么绑定表达式?
您可以使用RelativeSource
标记扩展名绑定Center并找到父Path实例对象,如下所示:
<EllipseGeometry x:Name="circle"
Center="{Binding Tag, RelativeSource={RelativeSource
Mode=FindAncestor, AncestorType=Path}}"
RadiusX="100"
RadiusY="100"/>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句