繁体   English   中英

从要设置样式的实例的属性中获取样式的值

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM