views:

629

answers:

2

I'm learning binding in WPF. I can get binding to work when 1) the text of one control goes directly to the text field of another and 2) when I manually configure binding in the code-behind file.

In the first scenario, I use purely XAML to configure the binding. Is it possible to access the source variable from XAML in the code-behind file?

<Window x:Class="DataBindingExperiments.MainWindow"
    ...
    xmlns:local="clr-namespace:DataBindingExperiments.DataSources">
    <Window.Resources>
        <local:Person x:Key="MyPerson" />
    </Window.Resources>
    <Grid>
        <StackPanel Orientation="Vertical">
            <GroupBox Header="XAML Binding" Width="Auto" Height="110" Margin="5,5,5,5">
                 <Grid>
                     ...    
                    <Grid.DataContext>    
                        <Binding Source="{StaticResource MyPerson}" />    
                    </Grid.DataContext>       
                    <TextBox Grid.Row="0" Grid.Column="1" Name="textBox_firstName" Text="{Binding Path=FirstName, UpdateSourceTrigger=PropertyChanged}" />    
                    <TextBox Grid.Row="1" Grid.Column="1" Name="textBox_lastName" Text="{Binding Path=LastName, UpdateSourceTrigger=PropertyChanged}"/>    
                    <TextBlock Grid.Row="2" Grid.Column="1" Name="textBox_fullName" Text="{Binding Source={StaticResource MyPerson}, Path=FullName}" />    
                </Grid>
...
...

In the above code, how do I access the instance of 'MyPerson' in the code-behind?

+3  A: 

I believe you'll have to do Person p = (Person)FindResource("MyPerson"); in the Window_Loaded event of your window. I don't think you can specify a Name for an item that's in a ResourceDictionary.

Pwninstein
+3  A: 

Well, in that case it's easy, because it's defined as a resource :

object MyPerson = FindResource("MyPerson");

In the general case, it's a bit more complex... Assuming you have a TextBox named textBox1, and its Text property is bound to the Name property of another object, you could do something like that :

BindingExpression expr = BindingOperations.GetBindingExpression(textBox1, TextBox.TextProperty);
object source = expr.DataItem;
Thomas Levesque
@Thomas: Very clever, I didn't know about the DataItem property :)
Pwninstein
Neither did I ;) I stumbled upon it while looking up BindingExpression in the documentation...
Thomas Levesque