【问题标题】:How to get height of an control in ViewModel如何在 ViewModel 中获取控件的高度
【发布时间】:2017-07-31 09:01:57
【问题描述】:

我的 Xaml 中有一个 ContentControl,我想在 ViewModel 中访问它的高度,我尝试在我的 ViewModel 中创建一个属性并通过 TwoWay 将它绑定到 ContentControl。但问题在于它将 ContentControl 高度设置为 0,这是该属性的默认值。

代码:

Xaml

<ContentControl x:Name="ContentControl"
                Content="{Binding ContentFrame}"
                HorizontalContentAlignment="Stretch"
                Height="{Binding ContentControlHeight, Mode=TwoWay}"
                VerticalContentAlignment="Stretch"></ContentControl>

ViewModel(使用 Fody 进行属性更改通知):

public double ContentControlHeight { get;放; }

【问题讨论】:

  • 你能添加你使用的代码吗?
  • 可以绑定Content控件的Loaded事件,获取控件的高度
  • @Arcana,谢谢。但我不想直接在后面的代码中访问控制。另请参阅我更新后的代码。
  • @Romasz。谢谢。会试一试的。
  • 如果您在项目中使用Template10,您可以在视图模型中创建DelegateCommand并将其绑定到Loaded事件

标签: c# xaml mvvm uwp winrt-xaml


【解决方案1】:

绑定到ActualHeight(可能还有宽度)不是一个好的选择,因为:

出于 ElementName 绑定的目的,ActualHeight 在更改时不会发布更新(由于其异步和运行时计算的性质)。不要尝试将 ActualHeight 用作 ElementName 绑定的绑定源。如果您有需要基于 ActualHeight 进行更新的场景,请使用 SizeChanged 处理程序。

值得遵循上述并使用SizeChanged事件。

【讨论】:

    【解决方案2】:

    添加到 Romasz 的建议,@ZeaShah,您可以创建一个自定义类并在其中注册 SizeChanged 事件。

    public class MyContentControl : ContentControl
    {
        public MyContentControl()
        {
            this.SizeChanged += MyContentControl_SizeChanged;
        }
    
        private void MyContentControl_SizeChanged(object sender, Windows.UI.Xaml.SizeChangedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("SizeChanged: height " + e.NewSize.Height + " width: " + e.NewSize.Width);
            CHeight = e.NewSize.Height;
        }
    
        public double CHeight
        {
            get { return (double)GetValue(CHeightProperty); }
            set { SetValue(CHeightProperty, value); }
        }
    
        // Using a DependencyProperty as the backing store for CHeight.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CHeightProperty =
            DependencyProperty.Register("CHeight", typeof(double), typeof(MyContentControl), new PropertyMetadata(0));
    }
    

    定义一个依赖属性并将其绑定到您的主页中:

    <local:MyContentControl x:Name="ContentControl"
                HorizontalContentAlignment="Stretch"
                VerticalContentAlignment="Stretch" CHeight="{Binding ContentControlHeight,Mode=TwoWay}">
    </local:MyContentControl>
    

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 2016-04-17
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多