0

我正在尝试使用 xaml 绑定 xamarin.forms 中的数据。但问题是它不起作用。我的xml代码:

<?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:BindingSample"
         x:Class="BindingSample.Test">
  <ContentPage.Resources>
    <ResourceDictionary>
      <OnPlatform x:Key="statusToImgConverter" 
            x:TypeArguments="local:StatusToImgSourceConverter"
            iOS="null"
            Android="local:StatusToImgSourceConverterDroid"
            WinPhone="local:StatusToImgSourceConverterUWP"/>
    </ResourceDictionary>
  </ContentPage.Resources>

  <ContentPage.BindingContext>
    <local:TestViewModel/>
  </ContentPage.BindingContext>

  <StackLayout>
    <Grid RowSpacing="1" ColumnSpacing="1">
      <Image Source="{Binding Enabled, Converter={StaticResource statusToImgConverter}}" />
      <Label Text="{Binding Enabled}" Grid.Column="1" Grid.ColumnSpan="4" />
    </Grid>
    <Button x:Name="enableBtn" Text="enable"/>
  </StackLayout>
</ContentPage>

视图模型类看起来像这样(我想使用 Fody 进行 INotifyPropertyChanged 代码生成)

[ImplementPropertyChanged]
class TestViewModel
{
    public TestViewModel()
    {
        Enabled = true;
    }

    bool Enabled { get; set; }
}

但问题是没有显示图像和标签。注释掉 ResourceDictionary 和 Image 不会产生任何影响(因此问题不在转换器中)。

我究竟做错了什么?

编辑 - 为内容页面添加代码。显示了按钮,但没有显示图像和标签。

public partial class Test : ContentPage
{
    public Protection()
    {
        InitializeComponent();

        enableBtn.Clicked += OnEnableClicked;
    }

    private void OnEnableClicked(object sender, EventArgs e)
    {
        //do nothing here at this time
    }

}
4

1 回答 1

0

最后我得到了错误的来源。正确的代码应该是:

<ResourceDictionary>
    <OnPlatform x:TypeArguments="local:StatusToImgSourceConverter" x:Key="statusToImgConverter">
      <OnPlatform.Android>
        <local:StatusToImgSourceConverterDroid/>
      </OnPlatform.Android>
      <OnPlatform.WinPhone>
        <local:StatusToImgSourceConverterUWP/>
      </OnPlatform.WinPhone>
    </OnPlatform>          
</ResourceDictionary>

在 Xaml。并且 Enabled 属性必须显式声明为 public。

于 2016-08-25T09:44:43.457 回答