Suiva
Suiva

Reputation:

WPF, passing variable to converter inside data template

I assume this is possible but not sure how to do it. I need to pass the value of a class level variable to a converter, from within side a data template.

<DataTemplate x:Key="ResponseItemTemplate">
        <StackPanel Orientation="Horizontal" >
            <StackPanel.Visibility>
                <MultiBinding Converter="{StaticResource VisibilityConverter}">
                    <Binding Path="Key"/>
                    <Binding Path="CurrentLanguage"/> 
                </MultiBinding> 
            </StackPanel.Visibility>

            <TextBox Width="200" Text="{Binding Value}" />
        </StackPanel>
    </DataTemplate>

The 'Key' value exists on the response item for the data template so this gets passed correctly, whereas the CurrentLanguage is a class variable and I can't get that to pass properly to the converter. Any ideas?

Upvotes: 2

Views: 4321

Answers (3)

suiva
suiva

Reputation:

Thanks for the replies, this is what I needed to use in the end:

 <Binding Path="DataContext.CurrentLanguage" RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type Window}}"/> 

Upvotes: 1

Cameron MacFarland
Cameron MacFarland

Reputation: 71936

If you define the converter as a resource, which you have, you can access it in the code behind. Once you have the converter you can then set a property on it.

var myVisConverter = (VisibilityConverter)window.Resources["VisibilityConverter"];
myVisConverter.CurrentLanguage = ...

EDIT Ok, if you're trying to get access to the parent DataContext from within the DataTemplate, there's a couple of options. Easiest is to name the control with the correct DataContext, then bind to that control like so...

<Binding Path="DataContext.CurrentLanguage" ElementName="nameGivenToElement" />

Josh Smith wrote an article with more ways of getting inherited DataContexts.

Upvotes: 0

Szymon Rozga
Szymon Rozga

Reputation: 18178

You can use the binding object as follows:

<Binding Source="{x:Static local:DataObject.MyData}" />

See: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/c94682e5-ad16-42f9-973f-fd7588a9c0b5.

Upvotes: 0

Related Questions