[英]WPF/C# Combobox DataBinding
To begin I would like to apologize for my english which is far from perfect (its not my native language...). 首先,我想为我的英语道歉,这远非完美(它不是我的母语......)。
I've a problem related to databinding in my XAML code. 我的XAML代码中存在与数据绑定相关的问题。 I've a combox which is supposed to list all graphical nodes that I drop on a custom canvas. 我有一个combox,它应该列出我放在自定义画布上的所有图形节点。 My graphical nodes are referenced in a list graphCanvas.uinodes
, and each node has a name
. 我的图形节点在列表graphCanvas.uinodes
中引用,每个节点都有一个name
。 And that's what I want to show in my combobox. 这就是我想在组合框中显示的内容。
So I tried something like this: 所以我尝试过这样的事情:
<ComboBox ItemsSource="{Binding ElementName=graphCanvas, Path=uinodes/name}"
Height="23" HorizontalAlignment="Left" Name="comboBox1"
VerticalAlignment="Top" Width="71" Foreground="Black" />
But even after drawing nodes on my canvas my combox is empty... 但即使在我的画布上绘制节点后,我的combox也是空的......
Any clue? 任何线索?
Thanks. 谢谢。
A binding using ElementName
finds the WPF element with that name. 使用ElementName
的绑定查找具有该名称的WPF元素。 I doubt that you've subclassed Canvas
and added a uinodes
property to it, which is the only way that Path
would find something even if the path syntax were correct, which it's not. 我怀疑你是否已经将Canvas
子类化并uinodes
添加了一个uinodes
属性,即使路径语法是正确的,这也是Path
找到的唯一方法,但事实并非如此。
If you look in the Output window when you run your program, you'll see an error message that tells you why the binding isn't working. 如果在运行程序时查看“输出”窗口,您将看到一条错误消息,告诉您绑定无法正常工作的原因。 That's a start. 那是一个开始。
But even then, you won't get what you want with this approach. 但即使这样,你也不会用这种方法得到你想要的东西。 What you probably want looks more like: 您可能想要的更像是:
<ComboBox ItemsSource="{Binding ElementName=graphCanvas, Path=uinodes}"
DisplayMemberPath="name"/>
or even 甚至
<ComboBox ItemsSource="{Binding ElementName=graphCanvas, Path=uinodes}">
<ComboBox.ItemTemplate>
<TextBlock Text="{Binding name}"/>
</ComboBox.ItemTemplate>
</ComboBox>
Your binding (specifically the Path
assignment) looks wrong. 您的绑定(特别是Path
分配)看起来不对。 Assuming uinodes
is an Enumerable of some sort it looks as though you are trying to bind to the `name' property of the collection, which does not exist. 假设uinodes
是某种类型的Enumerable,看起来好像你试图绑定到集合的`name'属性,这个属性不存在。 Try this: 尝试这个:
ItemsSource="{Binding ElementName=graphCanvas, Path=uinodes}" DisplayMemberPath="name"
As an aside, you can use the output window to see any binding errors. 另外,您可以使用输出窗口查看任何绑定错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.