Xamarin表格。将ViewModel参数传递给转换器

时间:2017-07-11 09:37:04

标签: c# xaml xamarin binding ivalueconverter

我正在尝试将viewmodel中定义的变量传递给自定义转换器。

这是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();
    }
}

这是ViewModel

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的变量传递给转换器的任何提示。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您想知道Selfies中的项目是否是最后一项。我认为你不能用IValueConverter做到这一点。我建议您在Model.Selfie中使用每次在集合中添加/删除项目时设置的属性。

相关问题