Xamarin MVVM Light ViewModelLocator 在 xaml 中设置 BindingContext
Posted
技术标签:
【中文标题】Xamarin MVVM Light ViewModelLocator 在 xaml 中设置 BindingContext【英文标题】:Xamarin MVVM Light ViewModelLocator setting BindingContext in xaml 【发布时间】:2016-12-26 15:09:41 【问题描述】:我想通过 xaml 而不是后端代码来设置 BindingContext。目前我是这样分配的:
public partial class MainPage : ContentPage
public MainPage()
InitializeComponent();
BindingContext = App.Locator.Main;
如何通过 Xaml 分配 BindingContext?我试过这样:
LoginPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Codesign.DtpMobilePortable.Views.LoginPage" BindingContext="Binding LoginPage, Source=StaticResource ViewModelLocator">
<StackLayout Spacing="20" Padding="50" VerticalOptions="Center">
<Entry x:Name = "EntryUsername" Text="Binding EntryUsernameText" Placeholder = "Username"/>
<Entry x:Name = "EntryPassword" Text="Binding EntryPasswordText" Placeholder = "Password" IsPassword = "true" />
<Button x:Name = "ButtonLogin"
Text = "Binding LoginButtonText"
TextColor = "White"
BackgroundColor = "Binding LoginButtonColor" Command="Binding LoginCommand"/>
</StackLayout>
</ContentPage>
App.xaml
<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModels="clr-namespace:Codesign.DtpMobilePortable.ViewModels;assembly=Codesign.DtpMobilePortable"
x:Class="Codesign.DtpMobilePortable.Views.App">
<Application.Resources>
<viewModels:ViewModelLocator
x:Key="ViewModelLocator" />
</Application.Resources>
</Application>
但我收到有关 StaticResource 不存在的错误。
【问题讨论】:
【参考方案1】:您应在页面标题上定义StaticResources
名称空间。
类似的东西:
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:Codesign.DtpMobilePortable;assembly=Codesign.DtpMobilePortable"
xmlns:Vm="clr-namespace:Codesign.DtpMobilePortable.ViewModel;assembly=Codesign.DtpMobilePortable"
x:Class="Codesign.DtpMobilePortable.Views.LoginPage"
BindingContext="Binding LoginPage, Source=StaticResource ViewModelLocator"
在我的示例代码中,StaticResources
是在上面的 xmlnss:local
命名空间中定义的。
【讨论】:
以上是关于Xamarin MVVM Light ViewModelLocator 在 xaml 中设置 BindingContext的主要内容,如果未能解决你的问题,请参考以下文章