views:

642

answers:

3

Hi, 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?

Thanks for your time

A: 

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.

Cameron MacFarland
Hi Cameron,Thanks for the reply, I'm tyring to use the MVVM pattern, so avoid using the code-behind. Just need a way to access the CurrentLanguage variable in the view model
A: 

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.

siz
A: 

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}}"/>