【问题标题】:Why is the Binding ItemSource property not found on my ViewModel?为什么在我的 ViewModel 上找不到 Binding ItemSource 属性?
【发布时间】:2020-03-02 14:29:05
【问题描述】:

我有 Xamarin Forms 应用程序来显示一副牌。 Deck 使用 App 类中的静态集合进行初始化。 (断点显示它已填充)。 MainPage 有一个 MainPageViewModel 设置为 BindingContext:

Public MainPage(){
    InitilizeComponent();
    BindingContext = new MainPageViewModel()
}

MainPageViewModel 有一个简单的属性来检索填充的Deck.Cards

public static IEnumerable<Card> Cards { get { return Deck.Cards; }}

这在主页的轮播集合中使用。

但是,视图是空的!我看到了

`[0: ] 绑定:在“mypackage.ViewModels.MainPageViewModel”上找不到“Cards”属性,目标属性“Xamarin.Forms.CarouselView.ItemsSource”

为什么找不到该属性?它是公开的和 IEnumerable。

【问题讨论】:

    标签: xamarin xamarin.forms data-binding


    【解决方案1】:

    假设您的 Xaml 当前有 ItemsSource={Binding Cards},然后将 Cards 设置为非静态,它会起作用。

    如果您想将 Cards 保留为静态属性,请使用 x:Static:

    ItemsSource={x:Static vm:MainPageViewModel.Cards}

    并确保在 Xaml 文件的顶部声明命名空间:xmlns:vm="clr-namespace:mypackage.ViewModels"

    【讨论】:

      【解决方案2】:

      改变这个:

      public static IEnumerable<Card> Cards { get { return Deck.Cards; }}
      

      到这里:

      public ObservableCollection<Card> Cards{ get {return new ObservableCollection<Card>(Deck.Cards.ToList()); }}
      

      希望这会有所帮助。

      【讨论】:

      • 啊!原始问题中有一个致命的错字。 MainPageViewModel 上定义了属性。对不起!
      • 修复它的是定义中的 x:Static 属性(请参阅已接受的答案)但投票赞成 - 如果需要通知更改,该集合应该是可观察的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      • 1970-01-01
      • 1970-01-01
      • 2011-03-03
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多