【问题标题】:Can I trigger an event in XAML when a control is less than a certain height?当控件小于某个高度时,我可以在 XAML 中触发事件吗?
【发布时间】:2017-02-03 03:18:10
【问题描述】:

我有一个两行网格,填充了图像和标签。标签具有锁定大小,而上面的图像随着网格缩小。当图像变得非常小以至于不可见时,例如

如果这完全是在 XAML 中实现的,并且通过某种触发器来寻找高度为

这可能吗?如果没有,在 c# 中检查图像高度的最优雅的解决方案是什么?

【问题讨论】:

  • 不能使用自定义转换器将可见性绑定到网格高度吗?
  • 我会谷歌自定义转换器并告诉你。干杯
  • @DanWheeler 转换器应该可以工作,但绑定到网格的ActualHeight,而不是HeightHeight 在运行时永远不会改变。 ActualHeight 会。
  • 非常感谢。它不能绑定到图像高度本身吗?无论如何,我只是好奇,这应该无关紧要。

标签: c# wpf xaml


【解决方案1】:

这是一种方法。首先,您需要一个转换器:

public class HeightToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var gridHeight = System.Convert.ToDouble(value);

        return gridHeight < 200 ? Visibility.Collapsed : Visibility.Visible;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

这里是 xaml:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:local="clr-namespace:WpfApplication1"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Title="MainWindow"
        Width="525"
        Height="350"
        mc:Ignorable="d">
    <Grid Name="grid">
        <Grid.Resources>
            <local:HeightToVisibilityConverter x:Key="HeightToVisibilityConverter" />
        </Grid.Resources>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <Label Grid.Row="0"
               Content="Some Text" />
        <Image Grid.Row="1"
               Source="zeros.jpg"
               Visibility="{Binding ElementName=grid,
                                    Path=ActualHeight,
                                    Converter={StaticResource HeightToVisibilityConverter}}" />

    </Grid>
</Window>

仅出于测试目的,如果网格高度小于 200,我将其设置为隐藏。您可以将其更改为适合您情况的任何内容。我并不是说这是最好的或唯一的解决方案,但希望它能让你开始......

【讨论】:

  • 感谢它完美地完成了这项工作。我基本上已经实现了这一点,但试图使用图像高度而不是网格,但图像 ActualHeight 始终为 0,所以它不起作用。这是怎么回事?
  • 我不是 WPF 专家,但是直到所有内容都布置好后才设置图像元素的 ActualHeight,因此第一次触发 Converter 时它的值为 0。出于某种原因,我不知道为什么,图像控件的 ActualHeight 属性在调整窗口大小时不会触发转换器,但是当您绑定到网格的 ActualHeight 时转换器会触发。希望有比我更专业的人加入,因为现在我很好奇!
  • 有趣。好吧,至少它的功能是我想要的,所以再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-20
  • 2012-04-10
  • 2011-10-11
  • 1970-01-01
  • 1970-01-01
  • 2011-09-06
相关资源
最近更新 更多