Question

Is it possible to subscribe to a Property of a specific UIElement in WPF?

I want to animate an UIElement as soon as the Heightvalue changes and add the new height to a list, but I don't see how I can subscribe to the HeightProperty?

Samplecode:

Something like this:

MainWindow.xaml:

<Window x:Class="BibVisualization.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <Border Background="Red" Width="30" Grid.Row="0" x:Name="myBorder">
        <TextBlock Text="Really really long text with wrapping, but the wrapping changes based on border's width"
               Width="{Binding ElementName=myBorder, Path=Width}"
               TextWrapping="Wrap" />
    </Border>
    <Button Grid.Row="1" Height="10" 
        Content="Make border bigger" Click="OnButtonClick" />
</Grid>
</Window>

MainWindow.xaml.cs

private void OnButtonClick(Object sender, RoutedEventArgs e)
{
    myBorder.Width += 10;
    //Bind to textblock's actualheight and execute OnHeightChange?
}

private int accumulatedChange;

private void OnHeightChange(Object sender, SomeEventArgs? e)
{
    accumulatedChange -= e.OldValue (if possible);
    accumulatedChange += e.NewValue;
}
Était-ce utile?

La solution

I think you can use the SizeChanged-Event of the FrameworkElement class to do what you want. All UIElements such as Button or Textblock derive from that class and therefore provide the event.

The SizeChangedEventArgs passed to registered method contains information if height or width has changed and provide the new values.

Autres conseils

If I understood properly you'd want to 'bind' to ActualHeight ?

Take a look at this link (http://meleak.wordpress.com/2011/08/28/onewaytosource-binding-for-readonly-dependency-property/) - it describes how it can be done using attached properties basically.

Also take a look at this answer of mine from the other day, which basically describes very similar problem.
https://stackoverflow.com/a/15367642/417747
(use link there to download the support code - you can bind to via Style or as described in the article - it's all similar thing)

What you'd need is to bind to ActiveHeight using the method described in the article, that changes your view-model's MyHeight property - handle it's set to get when the active height changes. Let me know if any questions.

Hope it helps.

You could use the DependencyPropertyDescriptor to add a ValueChangedHandler for the property:

DependencyPropertyDescriptor descriptor=DependencyPropertyDescriptor.FromProperty(UIElement.HeightProperty,typeof(UIElement));
descriptor.AddValueChanged(myUIElementToWatch, new EventHandler(OnHeightOfUiElementChanged));
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top