我正在创建一个具有图像和两行文本的'CardView'控件。 在我的页面上,如果我分配值,图像渲染,但是如果我使用数据绑定表达式它不工作...图像未绑定在XAML(Xamarin用户控件)
这里是控制:
public partial class CardView : Frame
{
public CardView()
{
BindingContext = this;
InitializeComponent();
}
public static readonly BindableProperty TitleProperty = BindableProperty.Create(nameof(Title), typeof(string), typeof(CardView), null, BindingMode.OneWay);
public string Title
{
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
public static readonly BindableProperty SubtitleProperty = BindableProperty.Create(nameof(Subtitle), typeof(string), typeof(CardView), null, BindingMode.OneWay);
public string Subtitle
{
get { return (string)GetValue(SubtitleProperty); }
set { SetValue(SubtitleProperty, value); }
}
public static readonly BindableProperty ImageSourceProperty = BindableProperty.Create(nameof(ImageSource), typeof(ImageSource), typeof(CardView), null, BindingMode.OneWay);
public ImageSource ImageSource
{
get { return (ImageSource)GetValue(ImageSourceProperty); }
set { SetValue(ImageSourceProperty, value); }
}
}
下面是该XAML控制:
<StackLayout HorizontalOptions="FillAndExpand" >
<Image HorizontalOptions="FillAndExpand"
Source="{Binding ImageSource}" />
<Label Text="{Binding Title}"
HorizontalOptions="FillAndExpand" />
<Label Text="{Binding Subtitle}"
HorizontalOptions="FillAndExpand" />
</StackLayout>
在我的ViewModel类:
public class SettingsPageViewModel : ViewModelBase
{
public SettingsPageViewModel(INavigationService navigationService) : base(navigationService)
{
Title = "Title";
}
public string Subtitle => "Subtitle";
public string Image => "icon.png";
}
这里是我的XAML为绑定失败的页面:
<controls:CardView Title="No Bound Title" Subtitle="No Bound SubTitle" ImageSource="icon.png">
</controls:CardView>
<controls:CardView BindingContext="{Binding .}" Title="{Binding Title}" Subtitle="{Binding Subtitle}" ImageSource="{Binding Image}">
</controls:CardView>
该控件的第一个实例呈现正确。 第二个实例不显示图像。
我已经删除了'BindingContext = this'并将'Binding'更改为'TemplateBinding',并且我得到了2个空的呈现控件。现在绑定根本不起作用。 –
这很奇怪。你在输出窗口中是否有错误?嵌套在ControlTemplate模板中的'StackLayout'是什么? – Grx70