从外部样式资源中查找元素,然后更改其自己的样式

时间:2018-10-01 11:22:11

标签: c# wpf xaml

只是出于好奇。以这种情况为例:

首先,在代码背后,我创建了三个复选框和三个椭圆:

for (int = 0; i < 3; i++){
    CheckBox checkBox = new CheckBox();
    checkBox.Style = (Style)this.FindResource("MyCheckBoxStyle");
    checkBox.Name = "checkBox_" + i;

    Path ellipsePath = new Path();
    ellipsePath.Fill = Brushes.Gray;

    EllipseGeometry ellipseGeometry = new EllipseGeometry();
    ellipseGeometry.Center = new Point(0, 0);
    ellipseGeometry.RadiusX = 2.5;
    ellipseGeometry.RadiusY = 2.5;

    ellipsePath.Data = ellipseGeometry;
    ellipsePath.Name = "ellipse_" + i;
}

现在是CheckBox样式:

<Style x:Key="MyCheckBoxStyle" TargetType="{x:Type CheckBox}">
        <Setter Property="Foreground" Value="Gray"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type CheckBox}"> 
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsChecked" Value="True">
                            <Setter Property="Background" TargetName="Border" Value="Green"/>
                            <Setter Property="BorderBrush" TargetName="Border" Value="Green"/>
                            <Setter Property="Foreground" Value="Green"/>
                <!-- Assumming the checkbox I'm checking is called "checkBox_1" I want to
                be able to find the ellipse path whose name is "ellipse_1" and change
                its style (for example, its color) -->
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

这个想法是,每个复选框都与一个椭圆关联。就像评论说的那样,假设我正在检查的复选框称为checkBox_1,我希望能够找到名称为ellipse_1的椭圆元素并更改其样式(例如其颜色)。

这可能吗?

修改

从您的答案中可以看到,如果复选框和椭圆都属于同一模板,则可以做到。我发现的问题(对不起,我忘了提及它)是当前我使用的是网格,其中一行包含椭圆,另一行包含复选框,这些复选框是在运行时创建的(这就是我使用的原因)代码隐藏):

enter image description here

1 个答案:

答案 0 :(得分:1)

使用如下所示的DataTemplate作为ItemsControl的ItemTemplate:

<DataTemplate x:Key="itemTemplate">
    <StackPanel Orientation="Horizontal">
        <Path x:Name="path" Fill="Gray" VerticalAlignment="Center" Margin="5">
            <Path.Data>
                <EllipseGeometry RadiusX="2.5" RadiusY="2.5"/>
            </Path.Data>
        </Path>
        <CheckBox x:Name="checkBox"/>
    </StackPanel>
    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding ElementName=checkBox, Path=IsChecked}"
                     Value="True">
            <Setter TargetName="path" Property="Fill" Value="Green"/>
        </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>