如何获取ItemsControl中的itemcontainer?

huangapple go评论67阅读模式
英文:

How to get the itemcontainer in Itemscontrol?

问题

以下是翻译好的内容:

界面:
如何获取ItemsControl中的itemcontainer?

代码:
如何获取ItemsControl中的itemcontainer?

我想获取ListView控件的itemcontainer,但始终得到null。
如果我从SelectionChanged事件中获取该项,代码将正常工作。

我不明白为什么会发生这种情况。

英文:

The UI:
如何获取ItemsControl中的itemcontainer?

The Code:
如何获取ItemsControl中的itemcontainer?

I want to get ListView control 's itemcontainer , but always get null.
If I get the item from the event SelectionChanged,the code will work correctly.

I can't understand why this happens.

答案1

得分: 0

如果你想使用ItemsControl.ContainerFromItem(Object) 方法,参数需要是你设置的数据,而不是来自 ListView.Items 的项对象。

应该像这样:

public List<Model> list { get;set; }
public MainPage()
{
    this.InitializeComponent();

    list = new List<Model>();
    list.Add(new Model { Name = "A" });
    list.Add(new Model { Name = "B" });
    list.Add(new Model { Name = "C" });
    list.Add(new Model { Name = "D" });
    mylist.ItemsSource = list;
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    ListViewItem item = mylist.ContainerFromItem(list[1]) as ListViewItem;
}
英文:

If you want to use ItemsControl.ContainerFromItem(Object) Method, the parameter needs to be the data that you set. Not an item object from the ListView.Items.

It should be something like this:

public List&lt;Model&gt; list { get;set; }
    public MainPage()
    {
        this.InitializeComponent();

        list = new List&lt;Model&gt;();
        list.Add(new Model { Name = &quot;A&quot; });
        list.Add(new Model { Name = &quot;B&quot; });
        list.Add(new Model { Name = &quot;C&quot; });
        list.Add(new Model { Name = &quot;D&quot; });
        mylist.ItemsSource = list;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        ListViewItem item = mylist.ContainerFromItem(list[1]) as ListViewItem;
    }

huangapple
  • 本文由 发表于 2023年6月12日 12:36:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76453680.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定