【问题标题】:Xamarin MVVM Light ViewModelLocator setting BindingContext in xamlXamarin MVVM Light ViewModelLocator 在 xaml 中设置 BindingContext
【发布时间】: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 不存在的错误。

【问题讨论】:

    标签: c# xaml mvvm xamarin


    【解决方案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 命名空间中定义的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-03
      • 1970-01-01
      • 2016-12-08
      • 2016-06-21
      相关资源
      最近更新 更多