How to simply bind this to ConverterParameter?

Svisstack picture Svisstack · May 7, 2011 · Viewed 28.8k times · Source

I have problem and i don't know how to solve this simple, i have many points like this, then solution should be not complicated.

I have main project with Settings and main XAML.

I have dependency project with Binding Converter and XAML File looks like:

<TextBlock Text="{Binding X.Y.Z, 
                 Converter={StaticResource ProbabilityConverter},                 
                 ConverterParameter=??????????????, Mode=OneWay}"
 />

This XAML file is loading by main XAML file from main project.

I must pass value of one property from Setting's to ConverterParameter, this parameter can be changing at runtime, then this is must be Binding, Binding i can do only for DependencyProperty in this case.

I must do DependencyProperty wrapper for this Setting property to solve this problem?

When i try set Binding in ConverterParameter i will get this exception at runtime:

A 'Binding' cannot be set on the 'ConverterParameter' property of type 'Binding'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

Answer

svick picture svick · May 7, 2011

You can bind to any property, it doesn't have to be a dependency property. But if you want your UI to reflect changes in the property immediately when they happen, you have two options:

  1. Make the property into an dependency property.
  2. Implement INotifyPropertyChanged on the type that holds the property and raise the PropertyChanged event when the property changes.

EDIT:

As pointed out in the edit to the question, it's not possible to bind to ConverterParameter. But you can use MultiBinding. For example, assume you want to bind to a date and give the converter culture specification as a parameter and refresh the binding when the culture changes (I'm not sure this is a good idea, but it serves well as an example). You could do it like this:

<TextBlock>
    <TextBlock.Resources>
        <local:DateCultureConverter x:Key="converter" />
    </TextBlock.Resources>
    <TextBlock.Text>
        <MultiBinding Converter="{StaticResource converter}">
            <Binding Path="Date" />
            <Binding Path="Settings.Culture" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

Here, both Date and Settings are properties on the current DataContext. DateCultureConverter implements IMultiValueConverter and you would probably put it in resources few levels up the hierarchy in real application.