简体   繁体   中英

How to update DataContext in WPF applications?

I am learning WPF and i've met an obstacle. I have a xaml file with Window:

...      
    <Window.DataContext>
        <local:LeaguesViewModel/>
    </Window.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Label VerticalAlignment="Center" HorizontalAlignment="Center" Margin ="20" Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2" Content="{Binding Path=HeaderText}"/>
        <ListView Grid.Column="0" Grid.Row="1" Margin="20" HorizontalAlignment="Center" VerticalAlignment="Center" ItemsSource="{Binding Path=Leagues}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}"/>
                    <GridViewColumn Header="Country" Width="120" DisplayMemberBinding="{Binding Country}"/>
                    <GridViewColumn Header="Num of teams" Width="120" DisplayMemberBinding="{Binding NumOfTeamsQualifiedToUCL}"/>
                </GridView>
            </ListView.View>
        </ListView>
        <TextBox Grid.Row="1" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding Path=SomeText}" />
    </Grid>
...

I would like to change a datacontext in a runtime. How to do it?

The short answer to how to change the data context of your Window , it's pretty easy and straightforward.

Let's suppose you have two ViewModel s, VM1 and VM2 . Initially you have VM1 set as the DataContext from your XAML , and that you want to change it to VM2 on a button click event. So all you want to do it set data context from code behind, like so:

private void Button_Click(object sender, RoutedEventArgs e)
{
    var vm2 = new VM2();
    DataContext = vm2;
}

But it's a different question why you would want to do that. Unless you know for certain that you want to change the DataContext of a View at runtime, you shouldn't. Typically you bind a ViewModel to a View and let it be. Any changes are done thought the member variables in that ViewModel . You probably want to read up more on this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM