ValueConverter - 绑定到self

时间:2017-05-17 13:17:20

标签: binding xamarin.forms ivalueconverter

我需要将标签绑定到复合值 - 由模型中的几个值组成。我试图使用ValueConverter这样做,但我无法弄清楚如何将对象本身传递给ValueConverter。这是我的代码: 在XAML:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:MyApp;assembly=MyApp"
         x:Class="MyApp.SavedDetailsPage">
  <ContentPage.Resources>
      <ResourceDictionary>
          <local:DetailsConverter x:Key="detailsCvt" />
      </ResourceDictionary>
  </ContentPage.Resources>
  ...
    <Label Text="{Binding ???, Converter={StaticResource detailsCvt}}" FontSize="Small" TextColor="Gray" />
  ...
在DetailsConverter.cs中

class DetailsConverter : IValueConverter
{
    object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        MyModel myModel = (MyModel)value;
        return (myModel.FirstName + " " + myModel.LastName);
    }
    ...

我尝试使用&#39;。&#39;对自己有约束力,但是没有用。

我通过向MyModel添加.This属性找到了解决方法,它可以访问对象本身,因此我可以通过&#39;这个&#39;在XAML绑定中,但不确定这是否是最佳方式。

提前致谢!

1 个答案:

答案 0 :(得分:4)

要绑定到ViewModel,您可以使用以下语法之一

{Binding}
{Binding .}
{Binding Path="."}