【问题标题】:How to bind to this in a xamarin-forms xaml-based view class如何在基于 xamarin-forms xaml 的视图类中绑定到 this
【发布时间】:2016-09-04 15:39:36
【问题描述】:

我想让 ViewModel 成为 View 类的一部分(它本身是基于 xaml 的)。我使用的框架是Xamarian.Forms

现在我尝试对 xaml 中的根对象 x:Name 执行操作,然后将绑定上下文设置为按名称引用它。

MainPage.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:App"
             x:Class="App.MainPage"
             x:Name="MainPageRoot">

  <Label 
    BindingContext="{x:Reference Name=MainPageRoot}"
    Text="{Binding Path=LabelText}"
    VerticalOptions="Center"
    HorizontalOptions="Center" />

</ContentPage>

我在MainPage.xaml.cs中添加了数据:

namespace App
{
    public partial class MainPage : ContentPage
    {
        public string LabelText;

        public MainPage()
        {
            LabelText = "Wow, this works";
            InitializeComponent();
        }
    }
}

但标签仍然是空的。

为什么这不起作用?以及如何使用来自this 的属性?

【问题讨论】:

    标签: xaml xamarin.forms


    【解决方案1】:

    问题是,LabelText 属性没有定义 getter,这段代码有效:

    public partial class MainPage : ContentPage
    {
        public string LabelText { get; }
    
        public MainPage()
        {
            LabelText = "Wow, this works";
            InitializeComponent();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-29
      • 2017-06-03
      • 2018-09-28
      • 2020-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      相关资源
      最近更新 更多