WPF Binding: How to databind to Grid?

一笑奈何 提交于 2019-12-07 06:56:34

问题


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.


回答1:


Instead of a Grid use a ContentPresenter like this:

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


来源:https://stackoverflow.com/questions/4493445/wpf-binding-how-to-databind-to-grid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!