如何从数据绑定 ItemsControl 获取模板化项目的实例? (WPF)
我有一个带有自定义
的
(还有一个自定义
,它只是一个 WrapPanel
),通过 ItemsSource
绑定到一个简单的可观察字符串集合。
DataTemplate
仅包含自定义 UserControl
的实例,其属性通过 {Binding}
绑定到字符串。
问题是因为我的数据项只是字符串,所以我需要以编程方式直接访问我的 UserControl
实例,但我似乎不知道如何!
我尝试过:
var item = tagBar.Items[ tagBar.Items.Count - 1 ];
...但这只是返回字符串。 另外:
var item2 = tagBar.ItemContainerGenerator.ContainerFromIndex( tagBar.Items.Count - 1 );
...返回一个 ContentPresenter
,我不知道如何使用 ContentPresenter
来访问我的 UserControl
实例>。
??
这类似于这个问题 ,但它从未得到正确的回答,并且也是特定于 Silverlight 的,而这是 WPF。
I have an <ItemsControl>
with a custom <DataTemplate>
(and also a custom <ItemsPanelTemplate>
that is just a WrapPanel
), bound via ItemsSource
to a simple observable collection of strings.
The DataTemplate
consists simply of an instance of a custom UserControl
whose properties are bound to the string via {Binding}
.
The problem is since my data items are just strings, I need to access the instances of my UserControl
directly programmatically, but I can't seem to figure out how!
I've tried:
var item = tagBar.Items[ tagBar.Items.Count - 1 ];
...but that just returns the string. Also:
var item2 = tagBar.ItemContainerGenerator.ContainerFromIndex( tagBar.Items.Count - 1 );
...returns a ContentPresenter
, and I can't figure out what to do with the ContentPresenter
to get to the instance of my UserControl
.
??
This is similar to this question, but it was never properly answered, and was also specific to Silverlight whereas this is WPF.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我发布的答案在这里处理聚焦 DataTemplate 内的元素,但它应该提供您需要的代码。 它涉及使用 DataTemplate 上的 FindName 方法来查找其中的控件。 如果你给你的 UserControl 一个名字,你应该是对的。
The answer I've posted over here deals with focusing an element inside a DataTemplate, but it should provide the code you need. It involves using the FindName method on your DataTemplate to find a control within it. If you give your UserControl a name you should be right.