[英]Get value for Style from property of the instance to be styled
我想在運行時創建元素並為其添加樣式。
給定以下Xaml,我想將屬性Center
的值綁定到樣式對象的實際值(請參閱main方法)。 我嘗試了不同的綁定符號,但是沒有成功(可能是因為我對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"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.