我的内容页面绑定到视图模型,但现在我需要将一些组件绑定到另一个视图模型。我的问题是,因为我已经将页面的bindingcontext绑定到视图模型,所以当我尝试将元素绑定到第二个视图模型时,{ BindingContext }语句将在绑定到绑定上下文的视图模型中查找属性。
所以我的问题是:当bindingcontext被设置为不同的视图模型时,如何简单地将一个元素绑定到另一个视图模型,然后绑定到另一个视图模型?
我试过的那些没用的东西
进行绑定。
代码
<ContentPage.Resources>
<ResourceDictionary>
<selectedDeal:DealsMViewModel x:Name="SelectedDeal" x:Key="SelectedDeal"/>
</ResourceDictionary>
</ContentPage.Resources>代码
<Image
x:Name="CompanyImage"
HeightRequest="200"
Aspect="AspectFill"
Source="{Binding Source={StaticResource SelectedDeal}, Path=DealImage}" />我已经将图像元素放入堆栈布局中,设置了的BindingContext,并尝试了这样的绑定:
代码
<Image
x:Name="CompanyImage"
HeightRequest="200"
Aspect="AspectFill"
Source="{Binding DealImage}"/>有两种方法使绑定工作
图像
代码
<Image
x:Name="CompanyImage"
HeightRequest="200"
Aspect="AspectFill"
Source="{Binding secondViewModel.DealImage}"/>设置图像源programatically.后的代码中的
代码
CompanyImage.Source = selectedDeal.DealImage;,但是我真正想要实现的是,如果可能的话,在XAML部分中学习这种方法!任何帮助都非常感谢!
发布于 2021-01-04 16:13:50
有几种方法可以实现你想要的.我会解释我处理ViewModel绑定的方式..。
public class ViewModelLocator
{
public ViewModelLocator()
{
DependencyService.Register<ILogService, LogService>();
if (!DesignMode.IsDesignModeEnabled)
{
DependencyService.Register<IDataStore, MockDataStore>();
}
else
{
DependencyService.Register<IDataStore, DesignDataStore>();
}
DependencyService.Register<LoginViewModel>();
DependencyService.Register<AboutViewModel>();
DependencyService.Register<SettingsViewModel>();
}
public LoginViewModel Login => DependencyService.Get<LoginViewModel>();
public AboutViewModel About => DependencyService.Get<AboutViewModel>();
public SettingsViewModel Settings => DependencyService.Get<SettingsViewModel>();
}<?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="Test.Views.LoginPage"
BindingContext="{Binding Login, Source={StaticResource Locator}}"
Title="LoginPage">
<ScrollView>
<Grid Margin="10,20,10,10" RowDefinitions="Auto,Auto,Auto,Auto">
<Label Grid.Row="0" Text="Username:" TextColor="Black" FontSize="14"/>
<Entry Grid.Row="1" x:Name="usernameEditor" Text="{Binding Username}" ClearButtonVisibility="WhileEditing" />
<Label Grid.Row="2" Text="Password:" TextColor="Black" FontSize="14"/>
<Entry Grid.Row="3" x:Name="passwordEditor" Text="{Binding Password}" IsPassword="True" ClearButtonVisibility="WhileEditing" />
<Button Grid.Row="6" Text="Login" Command="{Binding About.LoginCommand, Source={StaticResource Locator}}"/>
</Grid>
</ScrollView>
</ContentPage>https://stackoverflow.com/questions/65559689
复制相似问题