如何在 WPF 自定义控件中填充集合控件?
我正在学习在 WPF 中创建自定义控件的细节。到目前为止我理解的概念:
- 代码定义了控件的行为。
- 模板定义了控件的外观和感觉以及视觉方面。
- 您可以将模板的元素绑定到基础控制对象的属性。
如果模板有多个集合控件,例如 StackPanels,如何绑定它们以便由底层集合填充它们?我的第一个想法是利用每个 StackPanel
的 DataContext
,但我无法让它工作。我感觉我缺少一个可以为我解决这个问题的关键概念。
I'm learning the ins and outs of creating custom controls in WPF. The concepts I understand thus far:
- The code defines the control's behavior.
- The template defines the control's look and feel, the visual aspect.
- You can bind elements of the template to properties of the underlying control object.
If the template has multiple collection controls, such as StackPanels
, how do you bind them so that they are populated by underlying collections? My first inclination was to make use of the DataContext
of each StackPanel
, but I couldn't make it work. I get the feeling I'm missing a key concept that would solve this for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您希望在这些 StackPanel 中显示什么?面板用于排列项目。如果要显示项目集合,您可能需要使用 ItemsControl(或多种类型的 ItemsControl 之一)。 ItemsControl 非常强大 - 您可以指定项目的显示方式以及显示它们的面板的显示方式。您甚至可以指定该面板是 StackPanel。例如,
然后您想要绑定到项目列表,这使用 ItemsControl 非常容易!对于自定义控件,您可能希望在代码隐藏中公开控件本身的依赖属性,然后绑定到 XAML 中的依赖属性。例如,您可以为您拥有的各种列表创建依赖属性,如下所示:
然后您可以绑定 ItemsControls 的 ItemsSource 属性:(
在本例中,我假设自定义控件具有 ax:Name="root")
我希望这样有帮助!
What did you want to be in these StackPanels? Panels are used for arranging items. If you want to show a collection of items, you probably want to be using an ItemsControl (or one of the many types of ItemsControls). An ItemsControl is very powerful- you can specify how the items are displayed and how the panel that they're displayed on is displayed as well. You can even specify that the panel is a StackPanel. For example,
Then you wanted to bind to a list of items, which is very easy with an ItemsControl! In your case with the custom control, you may want to expose dependency properties on the control itself in the code-behind and then bind to those from the XAML. For example, you can create dependency properties for the various lists you have like this:
Then you can bind the ItemsSource property of your ItemsControls:
(in this case I assume that the custom control has a x:Name="root")
I hope this helps!
您无法直接绑定
StackPanel
的内容。它只是一个布局控件。但是,您可以做的是使用
ListBox
并将其 ItemsPanel 设置为StackPanel
(或您需要的任何其他布局控件)。然后,您可以将ListBox
的ItemsSource
设置为您想要的任何底层集合。You can't bind the contents of a
StackPanel
directly. It's simply a layout control.What you could do, however, is use a
ListBox
and set its ItemsPanel to be aStackPanel
(or whatever other layout control you need). Then you can set theListBox
'sItemsSource
to whatever underlying collection you want.