【问题标题】:Xamarin Forms Element Parent property is nullXamarin 表单元素父属性为空
【发布时间】:2015-10-27 12:25:21
【问题描述】:

我有一个ViewCell 用作ListView 的项目模板:

ListView details_list = new ListView ();
details_list.ItemTemplate = new DataTemplate(typeof(CartViewCell));

在 ViewCell 内部,我想要一个函数来访问 ListView 的 itemSource 以删除项目。我虽然可以通过访问ViewCell 中的Parent 属性来做到这一点

ListView parent = (ListView)this.Parent;

但是当我尝试这样做时,它显示父级为空。这是使用Parent 属性的不正确方式吗?我错过了什么?

【问题讨论】:

  • 你试过 view.ParentForAccessibility 吗?
  • 一般来说,您不应该从 UI 编辑 ListView.ItemsSource。你最好在你的 ViewModel 中拥有 ObservableCollection 和一个命令来操作它。
  • 所以我的 ViewModel 里面有一个 ObservableCollection。如何从 ViewCell 内部访问视图模型?我想将 MenuItem 与命令一起使用,但我不知道如何从该命令访问 ViewModel。
  • 我删除了我的答案,因为它在 Xamarin.Forms 中不起作用(在 Xamarin.Android 中起作用),对不起。

标签: c# android xamarin.android xamarin.forms xamarin-forms


【解决方案1】:

有一个覆盖方法你必须调用它然后父级不会为空

protected override void OnParentSet()
        {
            object view = Parent;
            base.OnParentSet();

            if (view.GetType() == typeof(Grid))
            {

            }
        }

【讨论】:

    【解决方案2】:

    有几种方法可以解决这个问题;两种可能性包括

    1. 使用命令

    在你的 ViewModel 中定义一个命令,

    // define a command property
    public ICommand DeleteCommand { get; set; }
    
    // in your constructor, initialize the command
    DeleteCommand = new Command<string>((id) =>
    {
      // do the appropriate delete action here
    }
    

    然后在你的 ViewCell 中绑定它

    <Button Command="{Binding DeleteCommand}" CommandParameter="{Binding ID}" Text="Delete" />
    
    1. 使用消息传递

    在您的 ViewModel 中,订阅一条消息:

    MessagingCenter.Subscribe<MyViewCell, string> (this, "Delete", (sender, id) => {
        // do the appropriate delete action here
    });
    

    在您的 ViewCell 中,每当他们单击按钮(或任何触发操作)时发送消息 - ID 应该是特定项目的标识符

    MessagingCenter.Send<MyViewCell, string> (this, "Delete", ID);
    

    【讨论】:

    • 但每个ViewCellbindingcontext 是我的视图模型中observeablecollection&lt;&gt; 中的一个对象。如何将ViewCell 绑定到实际的视图模型?
    • 啊,好点子。您可以在集合中的每个项目上定义命令,并让它调用父 VM 中的方法;但尝试消息传递方法可能更容易
    猜你喜欢
    • 2021-01-22
    • 2018-11-20
    • 1970-01-01
    • 2023-03-29
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    相关资源
    最近更新 更多