c# - 在 Xamarin.Forms 上的 XAML 中将 BindingContext 设置为 ViewModel

标签 c# xaml mvvm xamarin.forms binding-context

我想使用 Xamarin.Form 和 MVVM 开发一个简单的项目。在我的解决方案(名为 XamarinPOC)中,除了标准的 Xamarin.Forms 项目之外,我还有一个单独的模型项目 (XamarinPOC.Model) 和一个单独的 ViewModel 项目 (XamarinPOC.ViewModel)。

我在 XamarinPOC.ViewModel 项目中为 BaseViewModel 类(实现了 INotifyPropertyChanged 接口(interface))定义了一个抽象类,在我创建了一个 SummaryViewModel 类之后,它使用一个简单的属性扩展了 BaseViewModel 类:

namespace XamarinPOC.ViewModel
{
    public class SummaryViewModel : BaseViewModel
    {

        private string _test = "The binding is OK!";
        public String test
        {
            get
            {
                return _test;
            }
            set
            {
                _test = value;
                OnPropertyChanged("test");
            }
        }
        public SummaryViewModel(){}
    }
}

接下来,我在 XamarinPOC 项目中创建了一个简单的 ContentPage (SummatyView),它只包含一个标签,我想显示在 ViewModel 中定义的文本。我想使用 XAML 来定义 View 和绑定(bind),但是当我运行应用程序时,没有任何显示,我在编译时和运行时没有错误,但没有显示文本。我的 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"
             xmlns:local="clr-namespace:XamarinPOC.ViewModel,assembly=XamarinPOC.ViewModel"
             x:Class="XamarinPOC.Summary"
             Title="Summary List"
             BindingContext="XamarinPOC.ViewModel.SummaryViewModel">
  <StackLayout>
    <Label Text="{Binding test}"/>
  </StackLayout>
</ContentPage>

最后我的 app.cs 是:

 namespace XamarinPOC
{
     public class App : Application
     {
         public App()
         {
             MainPage = new Summary();
         }
     }
 }

在 XamarinPOC 项目中,我添加了对 XamarinPOC.ViewModel 和 XamarinPOC.Model 程序集的引用。

我认为问题出在绑定(bind)的 XAML 定义中,但我没有找到错误。我哪里错了?

最佳答案

在您的情况下,要将 View 绑定(bind)到 Xaml 中的 View 模型,请这样做

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:viewModels="clr-namespace:XamarinPOC.ViewModel; assembly=XamarinPOC.ViewModel"
             x:Class="XamarinPOC.Summary"
             Title="Summary List">
  <ContentPage.BindingContext>
    <viewModels:SummaryViewModel/>
  </ContentPage.BindingContext>
  <StackLayout>
    <Label Text="{Binding test}"/>
  </StackLayout>
</ContentPage>

我注意到的一个旁注是命名约定,最好将所有 ViewModel(即使只有一个 ViewModel)放在名为“ViewModels”的文件夹中,因此您的命名空间案例将是 XamarinPOC.ViewModels

关于c# - 在 Xamarin.Forms 上的 XAML 中将 BindingContext 设置为 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38552035/

相关文章:

wpf - 约什·史密斯 (Josh Smith) 的 RelayCommand 实现是否存在缺陷?

c# - IObservableCollection<ViewModel<T>> 包装 ObservableCollection<T>

c# - 在多线程中调用静态方法

c# - 如何在xaml/c#中旋转图像

c# - 如何设置非事件窗口的样式?

c# - WPF 默认 DynamicRessource 值

c# 通用存储库类

c# - 从 Java/C# 的角度理解 C++ 编译器

c# - 使用 GetType().Name 在事件处理程序中转换发件人对象

c# - 如何在两个不同的 View 模型中使用相同的模型数据?