根据网格的ColumnWidth更改矩形填充

时间:2010-05-05 10:41:39

标签: wpf styles datatrigger

基本上我想按照标题说的那样做,如果列宽为.50那么矩形应该是红色,如果它是.75那么它应该是琥珀色,如果它是1那么它应该是绿色。

我以为我可以通过DataTriggers实现这一点,但由于某种原因我得到“对象引用没有设置为对象的实例”错误,这是我的代码,我在这里遗漏了什么?

FYI宽度属性将通过timer_tick事件在后端更改。

<Grid x:Name="Grid1" Width="300" Height="30">
    <Grid.ColumnDefinitions>
        <ColumnDefinition x:Name="MyColumn1" Width=".50*"></ColumnDefinition>
        <ColumnDefinition x:Name="MyColumn2" Width=".50*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Grid.Triggers>
        <DataTrigger Binding="{Binding ElementName=MyColumn1,Path=Width}" Value=".50*">
            <Setter TargetName="rect" Property="Fill" Value="Red"></Setter>
        </DataTrigger>
        <DataTrigger Binding="{Binding ElementName=MyColumn1,Path=Width}" Value=".75*">
            <Setter TargetName="rect" Property="Fill" Value="Yellow"></Setter>
        </DataTrigger>
        <DataTrigger Binding="{Binding ElementName=MyColumn1,Path=Width}" Value="1">
            <Setter TargetName="rect" Property="Fill" Value="Green"></Setter>
        </DataTrigger>
    </Grid.Triggers>
    <Rectangle x:Name="rect" Grid.Column="0" HorizontalAlignment="Stretch"></Rectangle>
    <Rectangle Grid.Column="1" Fill="Blue"></Rectangle>

</Grid>

1 个答案:

答案 0 :(得分:7)

这对我有用。请注意,我使用StyleRectangle上设置了触发器。

<Grid x:Name="Grid1" Width="300" Height="30">
    <Grid.ColumnDefinitions>
        <ColumnDefinition x:Name="MyColumn1" Width=".50*"></ColumnDefinition>
        <ColumnDefinition x:Name="MyColumn2" Width=".50*"></ColumnDefinition>
    </Grid.ColumnDefinitions>

    <Rectangle x:Name="rect" Grid.Column="0" HorizontalAlignment="Stretch">
            <Rectangle.Style>
                <Style TargetType="{x:Type Rectangle}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ElementName=MyColumn1,Path=Width}" Value=".50*">
                            <Setter Property="Fill" Value="Red"></Setter>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding ElementName=MyColumn1,Path=Width}" Value=".75*">
                            <Setter Property="Fill" Value="Yellow"></Setter>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding ElementName=MyColumn1,Path=Width}" Value="1">
                            <Setter Property="Fill" Value="Green"></Setter>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Rectangle.Style>
    </Rectangle>
    <Rectangle Grid.Column="1" Fill="Blue"></Rectangle>
</Grid>