Silverlight XAML绑定元素名称

3

我有以下的XAML代码:

            <sdk:Label Content="{Binding RefreshTextToggle, Converter={StaticResource enumToText}, ConverterParameter=ItemsOfInterest,FallbackValue='Please select items of interest to you'}" 
                       Style="{StaticResource StandardLabel}"
                       Height="{Binding ElementName=ItemsOfInterest,Path=Height}"/>

            <ListBox Name="ItemsOfInterest" 
                     ItemsSource="{Binding Path=ItemsOfInterest}" 
                     Margin="5"
                     MinHeight="25"
                     Width="250"
                     HorizontalAlignment="Left">

ItemsOfInterest的高度是根据其中有多少元素而动态变化的。

有人看出我在高度绑定方面做错了什么吗?它与ItemsOfInterest的大小相差甚远。


我认为你最好使用网格或堆栈面板来协调这两个元素之间的大小关系。 - Keith Adler
我希望我能够,它们实际上在两个不同的网格列中。 - ErocM
2个回答

5
您应该绑定到ActualHeight,它指定了元素排列时的高度。Height属性允许您设置固定高度,但不告诉您排列后确切的高度。

实际上,这是Silverlight中已知的错误

您需要使用SizeChanged事件,如下所示:

<UserControl x:Class="SilverlightApplication3.MainPage"
        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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Button Content="Add Item" Click="Button_Click" />

        <ListBox x:Name="listBox1" Grid.Column="0" Grid.Row="1" VerticalAlignment="Top" SizeChanged="listBox1_SizeChanged" />
        <ListBox x:Name="listBox2" Grid.Column="1" Grid.Row="1" VerticalAlignment="Top" />

    </Grid>
</UserControl>

有以下代码后台:

using System.Windows;
using System.Windows.Controls;

namespace SilverlightApplication3 {
    public partial class MainPage : UserControl {
        public MainPage() {
            InitializeComponent();
        }

        private int counter;

        private void Button_Click(object sender, RoutedEventArgs e) {
            this.counter++;
            this.listBox1.Items.Add(counter.ToString());
        }

        private void listBox1_SizeChanged(object sender, SizeChangedEventArgs e) {
            this.listBox2.Height = this.listBox1.ActualHeight;
        }
    }
}

你可能可以将这个内容整合成一个很好的附加行为。
编辑: 以下是这样一个行为:
<UserControl x:Class="SilverlightApplication3.MainPage"
        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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SilverlightApplication3"
        mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Button Content="Add Item" Click="Button_Click" />

        <ListBox x:Name="listBox1" Grid.Column="0" Grid.Row="1" VerticalAlignment="Top" />
        <ListBox x:Name="listBox2" Grid.Column="1" Grid.Row="1" VerticalAlignment="Top" local:SizeSynchronizationBehavior.HeightElement="{Binding ElementName=listBox1}" />

    </Grid>
</UserControl>

使用代码后台:

using System;
using System.Windows;
using System.Windows.Controls;

namespace SilverlightApplication3 {
    public partial class MainPage : UserControl {
        public MainPage() {
            InitializeComponent();
        }

        private int counter;

        private void Button_Click(object sender, RoutedEventArgs e) {
            this.counter++;
            this.listBox1.Items.Add(counter.ToString());
        }
    }

    public static class SizeSynchronizationBehavior {

        #region Dependency Properties

        ///////////////////////////////////////////////////////////////////////////////////
        // HeightElement
        ///////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Identifies the <c>HeightElement</c> attached dependency property.  This field is read-only.
        /// </summary>
        /// <value>The identifier for the <c>HeightElement</c> attached dependency property.</value>
        public static readonly DependencyProperty HeightElementProperty = DependencyProperty.RegisterAttached("HeightElement",
            typeof(FrameworkElement), typeof(SizeSynchronizationBehavior), new PropertyMetadata(null, OnHeightElementPropertyValueChanged));

        /// <summary>
        /// Gets the value of the <see cref="HeightElementProperty"/> attached property for the specified <see cref="FrameworkElement"/>.
        /// </summary>
        /// <param name="obj">The object to which the attached property is retrieved.</param>
        /// <returns>
        /// The value of the <see cref="HeightElementProperty"/> attached property for the the specified <see cref="FrameworkElement"/>.
        /// </returns>
        public static FrameworkElement GetHeightElement(FrameworkElement obj) {
            if (obj == null) throw new ArgumentNullException("obj");
            return (FrameworkElement)obj.GetValue(HeightElementProperty);
        }

        /// <summary>
        /// Sets the value of the <see cref="HeightElementProperty"/> attached property to the specified <see cref="FrameworkElement"/>.
        /// </summary>
        /// <param name="obj">The object to which the attached property is written.</param>
        /// <param name="value">
        /// The new value of the <see cref="HeightElementProperty"/> attached property to the specified <see cref="FrameworkElement"/>.
        /// </param>
        public static void SetHeightElement(FrameworkElement obj, FrameworkElement value) {
            if (obj == null) throw new ArgumentNullException("obj");
            obj.SetValue(HeightElementProperty, value);
        }

        /// <summary>
        /// Called when <see cref="HeightElementProperty"/> is changed.
        /// </summary>
        /// <param name="d">The dependency object that was changed.</param>
        /// <param name="e">The <see cref="DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
        private static void OnHeightElementPropertyValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
            FrameworkElement element = d as FrameworkElement;
            if (element == null)
                return;

            SizeChangedEventHandler heightSizeChangedEventHandler = GetSizeChangedEventHandler(element);
            if (heightSizeChangedEventHandler == null) {
                heightSizeChangedEventHandler = (sender, eventArgs) => {
                    FrameworkElement he = GetHeightElement(element);
                    if (he != null)
                        element.Height = he.ActualHeight;
                };
                SetSizeChangedEventHandler(element, heightSizeChangedEventHandler);
            }

            FrameworkElement heightElement = e.OldValue as FrameworkElement;
            if (heightElement != null)
                heightElement.SizeChanged += heightSizeChangedEventHandler;

            heightElement = e.NewValue as FrameworkElement;
            if (heightElement != null)
                heightElement.SizeChanged += heightSizeChangedEventHandler;

        }

        ///////////////////////////////////////////////////////////////////////////////////
        // SizeChangedEventHandler
        ///////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Identifies the <c>SizeChangedEventHandler</c> attached dependency property.  This field is read-only.
        /// </summary>
        /// <value>The identifier for the <c>SizeChangedEventHandler</c> attached dependency property.</value>
        private static readonly DependencyProperty SizeChangedEventHandlerProperty = DependencyProperty.RegisterAttached("SizeChangedEventHandler",
            typeof(SizeChangedEventHandler), typeof(SizeSynchronizationBehavior), new PropertyMetadata(null));

        /// <summary>
        /// Gets the value of the <see cref="SizeChangedEventHandlerProperty"/> attached property for the specified <see cref="FrameworkElement"/>.
        /// </summary>
        /// <param name="obj">The object to which the attached property is retrieved.</param>
        /// <returns>
        /// The value of the <see cref="SizeChangedEventHandlerProperty"/> attached property for the the specified <see cref="FrameworkElement"/>.
        /// </returns>
        private static SizeChangedEventHandler GetSizeChangedEventHandler(FrameworkElement obj) {
            if (obj == null) throw new ArgumentNullException("obj");
            return (SizeChangedEventHandler)obj.GetValue(SizeChangedEventHandlerProperty);
        }

        /// <summary>
        /// Sets the value of the <see cref="SizeChangedEventHandlerProperty"/> attached property to the specified <see cref="FrameworkElement"/>.
        /// </summary>
        /// <param name="obj">The object to which the attached property is written.</param>
        /// <param name="value">
        /// The new value of the <see cref="SizeChangedEventHandlerProperty"/> attached property to the specified <see cref="FrameworkElement"/>.
        /// </param>
        private static void SetSizeChangedEventHandler(FrameworkElement obj, SizeChangedEventHandler value) {
            if (obj == null) throw new ArgumentNullException("obj");
            obj.SetValue(SizeChangedEventHandlerProperty, value);
        }

        #endregion // Dependency Properties
    }

}

这在我的 POC 中无法工作。另外,根据微软文档,ActualHeight 返回全屏模式下屏幕的垂直高度。 - Keith Adler
@Nissan - 你是否在查看 ListBox.ActualHeight? - CodeNaked
是的。如果您将其绑定到自动高度列表框,则高度不会更改。 - Keith Adler
@Nissan - 你是对的,看起来它在WPF中可以工作,但在Silverlight中不行。已更新,唯一已知的解决方法是使用SizeChanged。 - CodeNaked
看起来很不错。大家干得好。了解这些边角案例真是太好了。 - Keith Adler
非常感谢您所付出的努力,这对我来说是极大的帮助! - ErocM

0

我创建了一个简单的项目,复制了您遇到的问题:

  1. 添加了一个列表框和按钮
  2. 将按钮与列表框的高度挂钩
  3. 将列表框的高度设置为“自动”
  4. 创建了另一个按钮,用于向列表框中添加随机数量的项

运行后,列表框会增长,但相关按钮却不会。我现在正在努力确定失败的原因。

更新

好的,这个不起作用的原因是“自动”没有返回任何实际值,可以用来确定通过此绑定列表框的高度。我尝试了其他每种方法都无法解决这个问题。依赖绑定解决这个问题的解决方案将是有趣的。


按钮不会增长,因为它的高度将是自动(默认值),就像列表框一样。因此,它们只会占用足够显示其内容的垂直空间。 - CodeNaked
@CodeNaked 同意。但是即使在 ListBox 上指向其他路径,比如 ActualHeight、ItemsPanel.VisualTree.Height 等,最终结果都是一样的。 - Keith Adler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接