1

I've got a window with a field like this:

public partial class VariablesWindow : Window
{
    public Dictionary<string, string> Variables { get; private set; }

And then in the window's XAML, I've created a ListView. How do I set the ItemsSource to bind to Variables?

<ListView ItemsSource="???"

4 Answers 4

4

I think what ChrisF posted would work...

<ListView ItemsSource="{Binding Variables}" /> 

But you may need to explicity set the DataContext.

this.DataContext = this;
Sign up to request clarification or add additional context in comments.

3 Comments

Yes! Needed to set the DataContext too. The other answers were missing this :)
@Ralph: not quite true. The bindings will work fine unless someone sets the DataContext to something else.
@Jon: I didn't touch the DataContext property previously... I'm assuming by default it points to the control itself, not to the Window.
1

I think the following should work:

<ListView ItemsSource="{Binding Path=Variables}" />

I'm not in a position to double check this right now, so I'm not 100% of whether the Path= is needed or not.

There's more information on the binding syntax on the MSDN here and here. All their examples have the Path= syntax.

And you will have to set the DataContext.

Comments

1
<ListView ItemsSource="{Binding Path=Variables}" />

However, you may find it more useful to bind directly to keys or values, which you would do like this:

<ListView ItemsSource="{Binding Path=Variables.Values}" />

Update: These bindings will work as long as your DataContext is null or equal to this. Otherwise, you would need to use something more cumbersome, like

<ListView ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=x:Type Window}}, Path=Variables}

For binding help, take a look at this superb cheat sheet.

2 Comments

direct link: nbdtech.com/Free/WpfBinding.pdf (it's hidden on the page you linked to!)
@Ralph: I know. I didn't want to hotlink the PDF. :)
0

This works, but it's a bit ridiculously verbose:

ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=my:VariablesWindow, AncestorLevel=1}

Doesn't seem like the best way to do it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.