如何在Xamarin Forms的XAML Tabbed Page中设置BindingContext与SetBinding?
把已有Content Page集成到XAML编写的TabbedPage并设置绑定
我来帮你搞定这个问题!你要把已有的C#编写的Content Page放到XAML版的TabbedPage里,同时把C#里设置BindingContext和Picker绑定的逻辑转成XAML,其实分几步就能轻松实现:
第一步:在TabbedPage的XAML中引用你的Content Page
首先,在TabbedPage的XAML文件里,先引入你的MyPage所在的命名空间,然后直接把它作为标签页添加进去:
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:你的项目命名空间" <!-- 替换成MyPage实际所在的命名空间 --> x:Class="你的项目命名空间.你的TabbedPage类名"> <!-- 把你的MyPage作为一个标签页添加,设置标题 --> <local:MyPage Title="我的页面" /> <!-- 其他标签页可以在这里继续添加,比如另一个ContentPage --> <ContentPage Title="其他页面"> <!-- 这里放其他页面的内容 --> </ContentPage> </TabbedPage>
第二步:在XAML中设置BindingContext
你原来在C#里写的this.BindingContext = new MyPageViewModel();,转成XAML有两种常用方式,选哪种看你的需求:
方式一:在MyPage的XAML中直接设置(推荐)
如果你的MyPage还没有对应的XAML文件,建议新建一个和C#类同名的XAML文件(比如MyPage.xaml),把C#里的UI逻辑移到XAML里,然后直接在XAML中指定BindingContext:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:vm="clr-namespace:你的ViewModel所在的命名空间" <!-- 替换成MyPageViewModel的命名空间 --> x:Class="你的项目命名空间.MyPage"> <!-- 直接实例化ViewModel作为BindingContext --> <ContentPage.BindingContext> <vm:MyPageViewModel /> </ContentPage.BindingContext> <!-- 这里放你的页面UI,比如原来的Picker --> <Picker Title="请选择选项" ItemsSource="{Binding 你的ItemsSource属性名}" <!-- 替换成ViewModel中数据源的属性名 --> SelectedItem="{Binding 你的SelectedItem属性名}" /> <!-- 替换成ViewModel中选中项的属性名 --> </ContentPage>
方式二:在TabbedPage的XAML中给MyPage设置BindingContext
如果暂时不想给MyPage新建XAML文件,也可以直接在TabbedPage的XAML里给MyPage指定BindingContext:
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:你的项目命名空间" xmlns:vm="clr-namespace:你的ViewModel所在的命名空间" x:Class="你的项目命名空间.你的TabbedPage类名"> <local:MyPage Title="我的页面"> <local:MyPage.BindingContext> <vm:MyPageViewModel /> </local:MyPage.BindingContext> </local:MyPage> </TabbedPage>
补充说明:Picker的绑定转换
你原来在C#里对Picker的绑定(比如picker.SetBinding(Picker.SelectedItemProperty, nameof(MyPageViewModel.SelectedItem));),转成XAML就是用{Binding 属性名}的形式。注意你的MyPageViewModel一定要实现INotifyPropertyChanged接口,这样绑定的属性变化时UI才能同步更新哦。
内容的提问来源于stack exchange,提问作者I. Mendoza
相关产品推荐
相关产品推荐

