Setter目标名称未被识别。

4
我是一名WPF初学者,想使用DataTrigger编写WPF部分。
以下是所需逻辑:
如果变量“iBottleCount”≥10,则将标签的背景设置为绿色。 如果变量“iBottleCount”<10,则将标签的背景设置为黄色。 如果变量“iBottleCount”= 0,则将标签的背景设置为红色。
但我找不到目标名称为“StatusColor”的标签。
请查看下面的代码:
<DataGridTemplateColumn Header="Status" Width="80" >

<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <Grid>

            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="20" />
                <ColumnDefinition Width="1*" />
            </Grid.ColumnDefinitions>

            <TextBlock x:Name="StatusText" Height="15" HorizontalAlignment="Left" Margin="2,2,2,2" Text="" VerticalAlignment="Top" Grid.Row="0" Grid.Column="1"/>
            <Label x:Name="StatusColor" Content="" Background="green" HorizontalAlignment="Center" Margin="5,5,5,5" VerticalAlignment="Top" Height="10" Width="20" Grid.Row="0" Grid.Column="0"/>
        </Grid>
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>

<DataGridTemplateColumn.CellStyle>
    <Style TargetType="{x:Type DataGridCell}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding iBottleCount}" Value="=>10">

                <!-- PROBLEM IS IN THIS LINE -->
                <Setter TargetName="StatusColor" Property="Background" Value="Green" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</DataGridTemplateColumn.CellStyle>

</DataGridTemplateColumn>

那么问题出在哪里呢?标签是在几行之前定义的。
2个回答

7

模板有其独立的作用域,外部无法访问。在样式触发器中无法使用TargetName,如果需要更改标签,请向其样式添加触发器。


2

如果没有一个良好的最小完整可验证代码示例清楚地展示您想要做的事情,就不可能确定最佳修复方法。话虽如此...

首先,在H.B.的答案中的评论是正确的:您正在尝试访问命名元素,而该名称在您尝试访问它的点上不在范围内,并且即使您可以,Style触发器也无法使用TargetName属性。

当然,其中一种选择是将触发器移到模板中。但是,这将需要将模板与您正在使用的视图模型绑定。在您的情况下,这实际上可能是可以接受的。在问题中缺少足够的上下文以了解情况。

如果您更愿意保持现有设计,其中触发器位于DataGridCell样式中,那么您可以使用TemplateBinding来实现您想要的效果。例如...

在模板中:

<Label Content="" Background="{TemplateBinding Background}" HorizontalAlignment="Center"
       Margin="5,5,5,5" VerticalAlignment="Top" Height="10" Width="20"
       Grid.Row="0" Grid.Column="0"/>

然后,设置 DataGridCellBackground 属性将向下传播到模板中。也就是说,在您的样式触发器中:

<Setter Property="Background" Value="Green"/>

即,只需从现有代码中删除 TargetName 属性。

显然,这仅适用于您想在模板中设置单个 Background 值的情况。如果您有更复杂的场景,则需要更详细的内容。当然,不要忘记,如果您想为 Background 属性提供默认值,则需要在样式中包含一个非触发器的 <Setter .../> 元素来设置该默认值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接