user576838
user576838

Reputation: 875

Getting Parent Element Width for Converter

I'm trying to get the entire width for a current cell so I can draw a rectangle with a width of a certain percentage of that cell. I wasn't able to bind to set the Width property more than once, as suggested here. So my next attempt was to pass the grid with and UtilPct to the converter, subtract 150 (for the first column) and return my width. However, the grid doesn't have a width, it just say NaN in Snoop and the actual width is 0?

What is the best way to get the actual calculated width of my cell so I can adjust the rectangle's width? If anyone has any other approaches, I appreciated any help!

XAML:

<ItemsControl x:Name="icBrokerCreditList" Grid.Row="1" Grid.Column="1" ItemsSource="{Binding Path=BrokerCreditList}" HorizontalAlignment="Stretch">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid HorizontalAlignment="Stretch" x:Name="brokerGrid">
                <Grid.RowDefinitions>
                    <RowDefinition Height="20"></RowDefinition>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="150"></ColumnDefinition>
                    <ColumnDefinition x:Name="utilCol" Width="*"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <TextBlock Grid.Row="0" Grid.Column="0" Background="White" Foreground="Black" FontSize="12" Text="{Binding Path=BrokerName}"></TextBlock>
                    <Rectangle Fill="Green" Height="20" Grid.Row="0" Grid.Column="1">
                        <Rectangle.Width>
                            <MultiBinding Converter="{StaticResource PercentageConverter}">
                                <Binding Path="ActualWidth" ElementName="utilCol" />
                                <Binding Path="UtilPct" />
                            </MultiBinding>
                        </Rectangle.Width>
                    </Rectangle>
                </TextBlock>
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Upvotes: 1

Views: 885

Answers (1)

Murkaeus
Murkaeus

Reputation: 1441

You could use a ScaleTransform for the Rectangle's RenderTransform and bind the ScaleTransform's X property to your percent instead of setting a Width.

Note: that would left-align the Rectangle because the ScaleTransform CenterX property defaults to 0. Unfortunately, it uses absolute values instead of percentages, so you can't use CenterX with an unknown width to right-align. You'll have to create a third column with a Width set to "Auto" and put the Rectangle in there. To right-align, set the RenderTransformOrigin to "1,0".

Note: if your percentage is in fact a percentage (i.e. [0-100]%, "55%"), you'll have to pass it through a converter to divide it by 100 to get a proper scale.

Upvotes: 1

Related Questions