简体   繁体   中英

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. I've a combox which is supposed to list all graphical nodes that I drop on a custom canvas. My graphical nodes are referenced in a list graphCanvas.uinodes , and each node has a 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...

Any clue?

Thanks.

A binding using ElementName finds the WPF element with that name. 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.

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. 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. Try this:

ItemsSource="{Binding ElementName=graphCanvas, Path=uinodes}" DisplayMemberPath="name"

As an aside, you can use the output window to see any binding errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM