Reputation: 668
This may well have been asked and answered before but I really wasn't sure how to phrase the question.
I have a dictionary (MyLookup) and I want a control to bind to a particular key and value in the dictionary. The key for the dictionary is a string, and lets say the particular item is 'MyItem'. The output should be something like:
MyItem value: 43
One idea was to use a couple of text blocks and a tack panel, one for the key and one for the value. I tried to encapsulate the item of interest in the stack panel, but things get fruity when defining the binding path for the second text block
<StackPanel Orientation="Horizontal" Tag="MyItem">
<TextBlock Text ="{Binding Path=Tag, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}}, StringFormat={0} value:}"/>
<TextBlock Text ="{Binding Path=MyLookup[{Binding Path=Tag, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}}]}"/>
</StackPanel>
It might also be possible to do it with a single text block and some string formatting?
<TextBlock Text="{Binding Path=MyLookup[MyItem], StringFormat={0} value: {1}}"/>
Bleugh, it all falls apart there as there need to be 2 outputs?! My current thinking is to use a multi-converter to take the string and convert it to a string and an int, but I was wondering if thee were cunning things that I'm missing.
Upvotes: 0
Views: 87
Reputation: 8801
Hmm, what the h**k is this {Binding Path=MyLookup[{Binding Path=Tag, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}}]}
Take a look at ObjectDataProvider.
That bad ass allows you do craziest Bindings you can think of and all that is happening in XAML.
http://msdn.microsoft.com/en-us/library/system.windows.data.objectdataprovider%28v=vs.110%29.aspx
Upvotes: 0
Reputation: 69985
Once again, A Binding
can only be set on a DependencyProperty
of a DependencyObject
. You're trying to use a Binding
for the integer that specifies which key/value to look at from your Dictionary
, but you can't because it is an integer and not a DependencyProperty
.
Instead of doing this, you should create a view model that contains all of the data and functionality that your view requires. As @HighCore mentioned, once you have organised your data in the right way, then all of these nasty problems will disappear.
Upvotes: 2