xamarin中的数据绑定
本文关键字:数据绑定 xamarin | 更新日期: 2023-09-27 18:03:58
我试图在xamarin中绑定数据。使用xaml的表单。但问题是这行不通。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: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
}
}
终于找到了错误的来源。正确的代码应该是:
<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