Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ActualSize is not updating its value on WPF?

Tags:

.net

binding

wpf

I have the following code:

<Window x:Class="UnderstandSizing.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window2" Height="300" Width="300">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" x:Name="Column1" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <TextBox Grid.Column="0" Text="{Binding ActualWidth,ElementName=Column1,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}" />
</Grid>
</Window>

I expected to see at the textbox the value of the width of the column Column1 but all I can see is 0.

I've seen this and this but everywhere says that is related only to Silverlight, not WPF.

Edit Fixed a typo. Also to note that the Output window do not show any binding issue . What is strange to me is that it is working in the designer. It stops working only on runtime.

like image 717
Ignacio Soler Garcia Avatar asked Jan 25 '12 18:01

Ignacio Soler Garcia


2 Answers

Interesting...

As DanM found, ColumnDefinition.ActualWidth is not a dependency property so you wont get binding updates when it changes.

A workaround is to put a hidden control in the column and bind to it's ActualWidth like this:

    <ContentControl Visibility="Hidden" Grid.Column="0" HorizontalAlignment="Stretch" x:Name="hidden"/>
    <TextBox Grid.Column="0" Text="{Binding ActualWidth,ElementName=hidden,Mode=OneWay}" />
like image 120
Robert Levy Avatar answered Nov 12 '22 11:11

Robert Levy


Wouldn't this be a circular reference? The width of "Column1" is dependent on the Text of your TextBox, and the Text of your TextBox is dependent on the width of "Column1". I don't see how WPF could ever possibly resolve a value for this unless you explicitly set the width of either "Column1" or your TextBox.

Edit

Oh, I see the problem. ActualWidth is a double not a dependency property, so you will never receive an update when the value gets calculated.

You need to use @Robert Levy's suggestion of putting a dummy control in the space occupied by your TextBox and bind to the ActualWidth of that instead.

like image 4
devuxer Avatar answered Nov 12 '22 11:11

devuxer