[英]Xamarin Forms. Pass ViewModel parameter to converter
我正在尝试将视图模型中定义的变量传递给自定义转换器。
这是 xaml 文件:
<ContentPage.Resources>
<ResourceDictionary>
<converter:IsLastItemConverter x:Key="lastItemConverter" Collection="{Binding Selfies}" />
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
....
<local:Selfie IsLastItem="{Binding ID, Converter={StaticResource lastItemConverter}}" />
....
</ContentPage.Content>
这是后面的xaml.cs代码
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SelfieWall : BaseContentPage
{
public SelfieWall()
{
InitializeComponent();
this.BindingContext = new SelfieWallViewModel();
}
}
这是视图模型
public class SelfieWallViewModel : INotifyPropertyChanged
{
....
public List<Model.Selfie> Selfies { get; set; }
....
}
这是转换器
public class IsLastItemConverter : IValueConverter
{
public List<Selfie> Collection { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return true;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return true;
}
}
当我尝试加载上面 xaml 中定义的视图时,出现错误
System.NullReferenceException: Object reference not set to an instance of an object.
如果我删除错误消失
Collection="{Binding Selfies}"
来自 XAML。
关于如何将 ViewModel 的变量传递给转换器的任何提示。
如果我正确理解,您想知道“ Selfies
中的商品是否是最后一个。 我认为您无法使用IValueConverter做到这一点。 我建议您在Model.Selfie
中使用“属性”,您Model.Selfie
在“集合”中添加/删除项目时Model.Selfie
进行设置。
Xamarin.Forms最新版本不支持Converter Parameter绑定ViewModel属性。 它只接受直接从 UI/Xaml 传递的值。
这是一个解决方法。
public class BindablePropertyObject
{
/// <summary>
/// Populate converter parameter with this object.
/// Pass element reference as SOURCE and binding PROPERTY NAME.
/// Gets the binding context of SOURCE and property with the same name as PROPERTY NAME from the binding context.
/// Gets value of the property fetched from binding context.
/// Ex: Write in element ConverterParameter={utils:BindablePropertyObject PropertyName=property name, Source= {x:Reference element name}}
/// </summary>
/// <returns>Returns value of the property</returns>
public object GetValueFromPropertyType()
{
if (Source.IsNotNull() && Source is View view && view.BindingContext.IsNotNull())
{
var property = view.BindingContext.GetType().GetProperty(PropertyName);
if (property.IsNotNull())
{
return property.GetValue(view.BindingContext);
}
}
return null;
}
/// <summary>
/// Name of property which is binded to view
/// </summary>
public string PropertyName { get; set; }
/// <summary>
/// XF element which will be used to get binding context.
/// </summary>
public object Source { get; set; }
}
使用它,您可以在 Xaml 文件中创建一个 object 并传递源和属性名称。 GetValueFromPropertyType() 然后将从 Source.BindingContext 获取属性及其值,因为 Source 将是 XF 类型。 看法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.