Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Binding: How to databind to Grid?

I have created a class Account.
Next, I have created another class ReorderWindowController which has a field/property SelectedAccount of type Account.

Finally, I have written ReorderWindow WPF window xaml file:

<Window ...

    <Window.Resources>

        <contollers:ReorderWindowController x:Key="WindowController" />

        <DataTemplate DataType="{x:Type entities:Account}">
            <Grid Width="140" Height="50" Margin="5">
                <TextBlock Text="Some awesome text" />
                <TextBlock Text="{Binding Name}" />
                <TextBlock Text="Even more awesome text" />
            </Grid>
        </DataTemplate>

    </Window.Resources>

    <Grid>
        <Grid 
            Name="AccountGrid" 
            DataContext="{Binding Source={StaticResource ResourceKey=WindowController},
                          Path=SelectedAccount}">
        </Grid>
    </Grid>

</Window>

When I run my code, AccountGrid is not showing anything. Why? How do I make object data bind to the Grid and how do I make it use my data template? Thanks.

like image 792
Boris Avatar asked Dec 20 '10 20:12

Boris


1 Answers

Instead of a Grid use a ContentPresenter like this:

<Grid>         
<ContentPresenter
Name="AccountGrid"              
Content="{Binding Source={StaticResource ResourceKey=WindowController},                           Path=SelectedAccount}">  
   </ContentPresenter>
</Grid> 
like image 96
Daniel James Bryars Avatar answered Oct 23 '22 05:10

Daniel James Bryars