动态获取行定义 WPF MVVM 的高度
本文关键字:MVVM 高度 WPF 定义 获取 动态 | 更新日期: 2023-09-27 18:34:18
<Grid.RowDefinitions>
<RowDefinition Height="10"/>
<RowDefinition Height="*"/>
<RowDefinition Height="240"/>
</Grid.RowDefinitions>
这是我的用户控制器的行定义。我需要将第二行的高度获取到我的视图模型。我怎样才能得到它?
谢谢。
Kent Boogaart 编写了附加属性来观察元素的大小:
https://stackoverflow.com/a/1083733/4049478
这可能是使用 MVVM 时的最佳解决方案
观察者适应了你的问题(非常便宜的解决方案,但仍然是一个解决方案):
public class RowDefinitionObserver {
public static readonly DependencyProperty ObserveRowProperty = DependencyProperty.RegisterAttached(
"ObserveRow",
typeof(bool),
typeof(RowDefinitionObserver),
new FrameworkPropertyMetadata(OnObserveChanged));
public static readonly DependencyProperty ObservedRowHeightProperty = DependencyProperty.RegisterAttached(
"ObservedRowHeight",
typeof(double),
typeof(RowDefinitionObserver));
public static bool GetObserveRow(FrameworkElement frameworkElement) {
return (bool)frameworkElement.GetValue(ObserveRowProperty);
}
public static void SetObserveRow(FrameworkElement frameworkElement, bool observe) {
frameworkElement.SetValue(ObserveRowProperty, observe);
}
public static double GetObservedRowHeight(FrameworkElement frameworkElement) {
return (double)frameworkElement.GetValue(ObservedRowHeightProperty);
}
public static void SetObservedRowHeight(FrameworkElement frameworkElement, double observedHeight) {
frameworkElement.SetValue(ObservedRowHeightProperty, observedHeight);
}
private static void OnObserveChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) {
var frameworkElement = (FrameworkElement)dependencyObject;
if ((bool)e.NewValue) {
frameworkElement.SizeChanged += OnFrameworkElementSizeChanged;
UpdateObservedSizesForFrameworkElement(frameworkElement);
} else {
frameworkElement.SizeChanged -= OnFrameworkElementSizeChanged;
}
}
private static void OnFrameworkElementSizeChanged(object sender, SizeChangedEventArgs e) {
UpdateObservedSizesForFrameworkElement((FrameworkElement)sender);
}
private static void UpdateObservedSizesForFrameworkElement(FrameworkElement frameworkElement) {
Grid g = frameworkElement as Grid;
if (g != null) {
if (g.RowDefinitions.Count > 1) {
SetObservedRowHeight(g, g.RowDefinitions[1].ActualHeight);
}
}
}
}
用法:
<Grid attachedProperties:RowDefinitionObserver.ObserveRow="True"
attachedProperties:RowDefinitionObserver.ObservedRowHeight="{Binding RowHeight, Mode=OneWayToSource}"><!--RowHeight is a double Property in your ViewModel-->
<Grid.RowDefinitions>
<RowDefinition Height="10"/>
<RowDefinition Height="*"/>
<RowDefinition Height="240"/>
</Grid.RowDefinitions>
<Grid/>
<Grid Grid.Row="1" Background="Red"/>
<Grid Grid.Row="2"/>
</Grid>
要使其具有适应性,您必须为 RowDefinition 的索引添加一个 DP