MAUI中Syncfusion Popup绑定独立ContentView数据失败求助
解决MAUI中Syncfusion Popup使用ContentView时数据绑定失效的问题
问题根源
你的MyView构造函数中设置了BindingContext = this,这会覆盖从父级(Popup的ContentTemplate)继承的BindingContext,导致ContentView内部的绑定无法关联到页面的ViewModel。原本Data="{Binding MyString}"是期望绑定到ViewModel的MyString,但因为BindingContext被改成了MyView自身,这个绑定会失效。
修复方案
1. 移除MyView构造函数中的BindingContext赋值
修改MyView.cs,删除BindingContext = this这一行:
namespace MinimalNotWorkingExample; public partial class MyView : ContentView { public static readonly BindableProperty DataProperty = BindableProperty.Create("Data", typeof(string), typeof(MyView)); public string Data { get => (string)GetValue(DataProperty); set => SetValue(DataProperty, value); } public MyView() { InitializeComponent(); } }
2. 修改MyView.xaml中的绑定路径
由于ContentView现在继承父级的BindingContext(即ViewModel),内部Label需要通过RelativeSource指定绑定源为ContentView本身,才能正确访问Data属性:
<?xml version="1.0" encoding="utf-8" ?> <ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:MinimalNotWorkingExample" x:Class="MinimalNotWorkingExample.MyView"> <VerticalStackLayout> <Label Text="If you can Read this, the ContentView was loaded. IF you can see the same text below as in the header, the Binding is working." VerticalOptions="Center" HorizontalOptions="Center" TextColor="Black"/> <Label Text="{Binding Data, Source={RelativeSource AncestorType={x:Type local:MyView}}}" VerticalOptions="Center" HorizontalOptions="Center" TextColor="Black"/> </VerticalStackLayout> </ContentView>
验证效果
修改后,点击第一个按钮弹出使用ContentView的弹窗时,Label的内容会正确绑定到ViewModel的MyString,和弹窗标题保持一致,绑定功能恢复正常。
内容的提问来源于stack exchange,提问作者Thorsten Schmitz
相关产品推荐
相关产品推荐

