在元素的值发生变化后执行方法

本文关键字:变化 执行 方法 元素 | 更新日期: 2023-09-27 18:03:48

是否可以在WPF中订阅特定元素的属性?

我想动画一个UIElement一旦height值改变,并添加新的高度到一个列表,但我不知道我怎么能订阅HeightProperty?

Samplecode:

像这样:

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;
}

在元素的值发生变化后执行方法

我认为你可以使用FrameworkElement类的SizeChanged-Event来做你想做的事情。所有UIElement,如ButtonTextblock,都派生自该类,因此提供事件。

传递给注册方法的SizeChangedEventArgs包含了高度或宽度发生变化的信息,并提供了新的值

如果我理解正确的话,您想要'绑定'到ActualHeight ?

看看这个链接(http://meleak.wordpress.com/2011/08/28/onewaytosource-binding-for-readonly-dependency-property/) -它描述了如何使用附加属性。

也看看我前几天的回答,它基本上描述了非常相似的问题。
https://stackoverflow.com/a/15367642/417747
(使用链接下载支持代码-您可以通过Style或文章中描述的方式绑定-都是类似的事情)

您需要的是使用本文中描述的方法绑定到ActiveHeight,这将更改视图模型的MyHeight属性-处理它的set以在活动高度发生变化时获得。如果有任何问题请告诉我。

希望能有所帮助。

您可以使用DependencyPropertyDescriptor为属性添加ValueChangedHandler:

DependencyPropertyDescriptor descriptor=DependencyPropertyDescriptor.FromProperty(UIElement.HeightProperty,typeof(UIElement));
descriptor.AddValueChanged(myUIElementToWatch, new EventHandler(OnHeightOfUiElementChanged));