【问题标题】:Xamarin Forms. Pass ViewModel parameter to converterXamarin 形式。将 ViewModel 参数传递给转换器
【发布时间】:2017-07-11 09:37:04
【问题描述】:

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

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

【问题讨论】:

  • 我阅读了该链接,但没有提及如何从视图模型绑定到转换器。
  • 您必须设置 BindingContext。发布您的 ViewModel 和完整的 XAML...您应该在 XAML 中定义您的转换,例如 。什么是 Collection="{Binding Selfies}"??
  • 查看我编辑的帖子

标签: c# xaml xamarin binding ivalueconverter


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-08
    • 2018-01-09
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2014-09-15
    • 1970-01-01
    相关资源
    最近更新 更多