我有一个页面,我将命令绑定到按钮。当我点击它时,我调用了一个方法,我从API中获取了我想要的数据。如果我不想只在视图中绑定数据,还要在代码后面使用这些数据?! 让我们说这是我的观点:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="HelloWorld.Pages.JohnDoePage"
xmlns:local="clr-namespace:Xamarin.Forms.Maps;assembly=Xamarin.Forms.Pages"
xmlns:vm="clr-namespace:HelloWorld.ViewModel;assembly=HelloWorld">
<StackLayout Padding="20, 10" HorizontalOptions="Center">
<Button Command="{Binding JohnDoe}"
Text="Data about John Doe" />
</StackLayout>
</ContentPage>
代码behihnd:
Models.Info info;
public JohnDoePage(Models.Info info)
{
InitializeComponent();
BindingContext = new InfoDetailsViewModel(info);
this.info= info;
// i want to use the data here
//using the data
}
视图模型:
Data _data;
public Data Data
{
get { return _data; }
set
{
if (value == _data) return;
_data = value;
OnPropertyChanged();
}
}
public ICommand JohnDoe
{
get
{
return new Command(async () =>
{
var Dataa = await _apiServices.InfoAboutJohnDOe();
});
}
}
我获得所需数据的服务是可以的。我使用相同的viewmodel来绑定不同的命令,我不知道这是否可行,所以我被卡住了。知道如何使用我在视图代码中获得的数据?在此先感谢!!
答案 0 :(得分:1)
为什么不保持对VM的类级别引用?
Models.Info info;
InfoDetailsViewModel vm;
public JohnDoePage(Models.Info info)
{
InitializeComponent();
vm = new InfoDetailsViewModel(info);
BindingContext = vm;
this.info= info;
}
答案 1 :(得分:1)
将服务电话的结果保存为公共财产
JohnDoePageViewModel dataContext = (JohnDoePageViewModel)this.DataContext;
并将JohnDoePage的DataContext保存为成员。
var data = dataContext.Dataa;
因为那样你就可以从ViewModel获取信息。
{{1}}
这有帮助吗?