gpt4 book ai didi

c# - Xamarin MVVM Light ViewModelLocator 在 xaml 中设置 BindingContext

转载 作者:行者123 更新时间:2023-12-03 10:43:41 24 4
gpt4 key购买 nike

我想通过 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>

应用程序.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 不存在的错误。

最佳答案

您应定义 StaticResources页面标题上的 namespace 。

类似的东西:

<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}}"

在我的示例代码中我的 StaticResourcesxmlnss:local 上定义上面的命名空间。

关于c# - Xamarin MVVM Light ViewModelLocator 在 xaml 中设置 BindingContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39039328/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com