Mania
Mania

Reputation: 1738

How to bind to property of object returned by converter

I'm trying to bind to a value, run a converter over it, and then display a property of that value. Having the Converter directly return the property I want wouldn't work, as I need property changes to be tracked.

What I'm trying to achieve would be something like this:

// NOTE: FOLLOWING IS NOT SUPPORTED BY WPF
// A 'Binding' cannot be set on the 'Source' property of type 'Binding'.
// A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

Text={Binding TextField Source={Binding SomeValue, Converter={StaticResource GetObjectFromValueConverter}}}`

Ideally, this would all be wrapped up in a simple markup extension.

Text={l:GetTextField SomeValue}

Problem is, I haven't been able to find any way to do this other than bind the Tag of the element to the converter, and then bind the target field to the property as follows:

Tag={Binding SomeValue, Converter={StaticResource GetObjectFromValueConverter}}
Text={Binding Tag.TextField, RelativeSource={RelativeSource Self}}

This is obviously cumbersome, limited (you only get one Tag field) and feels abusive. How else can I go about achieving what I want whilst monitoring for changes of TextField though?

Upvotes: 1

Views: 379

Answers (1)

CodeNaked
CodeNaked

Reputation: 41393

You can bind the DataContext of the TextBox, instead of the Tag. That will make your other bindings much simpler:

DataContext="{Binding SomeValue, Converter={StaticResource GetObjectFromValueConverter}}"
Text="{Binding TextField}"

This assumes that you do not have any other bindings on the TextBox that require the inherited DataContext. For example, in the bindings below Text2 would be broken:

DataContext="{Binding SomeValue, Converter={StaticResource GetObjectFromValueConverter}}"
Text2="{Binding SomeOtherValue, Converter={StaticResource GetObjectFromValueConverter}}"
Text="{Binding TextField}"

Also, if you have a more complex control other than TextBox, the DataContext for any controls below it in the logical/visual tree will also be affected.

Upvotes: 3

Related Questions