【问题标题】:Execute method after value from UIElement changesUIElement 中的值更改后执行方法
【发布时间】:2013-03-01 19:23:46
【问题描述】:

是否可以订阅 WPF 中特定 UIElement 的属性?

我想在 Heightvalue 更改后立即为 UIElement 设置动画并将新高度添加到列表中,但我不知道如何订阅 HeightProperty?

示例代码:

类似这样的:

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

【问题讨论】:

    标签: c# wpf animation uielement


    【解决方案1】:

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

    传递给注册方法的SizeChangedEventArgs 包含高度或宽度是否已更改的信息并提供新值。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 听起来很有希望,但如果我在初始化窗口后这样做只会触发一次,无论如何谢谢!
      【解决方案3】:

      如果我理解正确,您想“绑定”到ActualHeight 吗?

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

      也看看我前几天的这个答案,基本上描述了非常相似的问题。
      https://stackoverflow.com/a/15367642/417747
      (使用那里的链接下载支持代码 - 您可以通过Style 绑定或如文章中所述 - 都是类似的东西)

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

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-26
        • 1970-01-01
        相关资源
        最近更新 更多