我想通过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不存在的错误。
答案 0 :(得分:0)
您应在页眉上定义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
命名空间中定义。