【发布时间】:2021-11-20 19:59:37
【问题描述】:
- 我正在尝试将 ImageButton Source 连接到我的 MainPage 中的可变字符串属性。我不确定它是否是正确的方法。但是,我正在尝试找到一种使用绑定表达式将两者绑定在一起的方法。
namespace MyNameSpace
{
public partial class MainPage : ContentPage, INotifyPropertyChanged
{
public new event PropertyChangedEventHandler PropertyChanged;
public String One => "MyNameSpace.Images.Blue.jpg";
public MainPage()
{
InitializeComponent();
}
protected override void OnPropertyChanged ([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}
这是我创建的 MarkUpExtension,用于在使用嵌入式图像资源时将字符串作为资源提供。
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace MyNameSpace
{
[ContentProperty("ResourceId")]
public class EmbeddedImage : IMarkupExtension
{
public string ResourceId { get; set;}
public object ProvideValue(IServiceProvider serviceProvider)
{
if (String.IsNullOrWhiteSpace(ResourceId))
return null;
return ImageSource.FromResource(ResourceId);
}
}
}
这就是我试图在 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:MyNameSpace"
x:Class="MyNameSpace.MainPage"
x:Name = "Main">
<StackLayout
BindingContext="{x:Reference Name=Main }">
<Image
Source="{local:EmbeddedImage ResourceId = {Binding One}}">
</Image>
</StackLayout>
</ContentPage>
显然它不起作用...我收到错误:
MainPage.xaml(13, 12):[XFC0009] 找不到“ResourceId”的属性、BindableProperty 或事件,或者值和属性之间的类型不匹配。
也许这不是这样做的方法...有不同的方法吗?
【问题讨论】:
标签: c# xaml xamarin.forms data-binding markup-extensions