开发者

Change Rectangle Fill Based on ColumnWidth of a grid

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*"><开发者_C百科;/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>


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜