views:

90

answers:

1

Essentially i want to do as the title says, if the columnwidth is .50 then the rectangle should be red, if it's .75 then it should be amber, and if it's 1 then it should be green.

I thought I could achieve this with DataTriggers but for some reason I am getting "Object Reference Not Set To An Instance Of An Object" error, here is my code, am I missing something here?

FYI the width property will be changed in the backend through a timer_tick event.

<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  A: 

This worked for me. Please note I used a Style to set triggers on a Rectangle.

<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>
wpfwannabe
Thanks, i can't believe it was that easy :-)
Coesy