MAUI:如何将RowDefinition的Height绑定到View后台代码变量
解决Grid行高绑定到页面代码后台属性的问题
你的问题出在错误地给Grid.RowDefinitions设置BindingContext,而且RelativeSource Self指向的是RowDefinitions集合本身,不是MainPage实例。直接给RowDefinition的Height绑定指定正确的数据源即可,以下是两种可行方案:
方案一:使用RelativeSource绑定到MainPage
直接在RowDefinition的Height绑定中,通过RelativeSource向上查找MainPage类型的祖先元素:
<Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="75"/> <RowDefinition Height="10"/> <!-- 绑定到MainPage的TestHeight属性 --> <RowDefinition Height="{Binding TestHeight, RelativeSource={RelativeSource AncestorType={x:Type local:MainPage}}}" /> <RowDefinition Height="10"/> </Grid.RowDefinitions>
注意:需要在XAML头部引入MainPage所在的命名空间(假设命名空间为YourNamespace):
xmlns:local="clr-namespace:YourNamespace"
方案二:使用ElementName绑定
先给MainPage根元素设置x:Name:
<Page x:Class="YourNamespace.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="ThisMainPage">
然后在RowDefinition中通过ElementName绑定:
<Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="75"/> <RowDefinition Height="10"/> <RowDefinition Height="{Binding TestHeight, ElementName=ThisMainPage}" /> <RowDefinition Height="10"/> </Grid.RowDefinitions>
关键注意点
TestHeight必须是依赖属性或实现INotifyPropertyChanged的属性,否则绑定不会生效:
定义为依赖属性(推荐用于页面级属性)
public static readonly DependencyProperty TestHeightProperty = DependencyProperty.Register(nameof(TestHeight), typeof(GridLength), typeof(MainPage), new PropertyMetadata(new GridLength(50))); public GridLength TestHeight { get { return (GridLength)GetValue(TestHeightProperty); } set { SetValue(TestHeightProperty, value); } }
实现INotifyPropertyChanged(适合动态更新场景)
using System.ComponentModel; using System.Runtime.CompilerServices; public partial class MainPage : Page, INotifyPropertyChanged { private GridLength _testHeight = new GridLength(50); public GridLength TestHeight { get => _testHeight; set { _testHeight = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
内容的提问来源于stack exchange,提问作者SEGMK
相关产品推荐
相关产品推荐

