Home > Mobile >  How to bind to a field without specifying Path or Datacontext?
How to bind to a field without specifying Path or Datacontext?

Time:12-07

Note: The whole source code contains multiple files and 100s of lines of code so, I can't post everything here. The complete source code is available at this Github Repo


I am new to WPF and following books to gather knowledge. So far, in all the example of books, I have seen that either we need to specify the ElementName Path or have a DataContext for binding.

But in a Youtube tutorial (with Source Code at GIT, the UI elements are binded to the fields directly without specifying any DataContext. For example, in the code snippet below, the Text attribute of the TextBox has been binded to Username without specifying any DataContext or Path:

    <Grid Grid.Row="1" Margin="0 25 0 0">
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
        </Grid.RowDefinitions>

        <TextBlock Grid.Row="0" Text="Username" />
        <TextBox
            Grid.Row="1"
            Margin="0 5 0 0"
            Text="{Binding Username, UpdateSourceTrigger=PropertyChanged}" />
    </Grid>

QUESTION: How is the above Binding working? How does the Binding comes to know which Username has been specified? Here is the link to the complete source code of the MakeReservatoonView.xaml

CodePudding user response:

In App.xaml.cs, you can see that the MainWindow DataContext is set to MainViewModel.
In MainWindow, you have

<ContentControl Content="{Binding CurrentViewModel}" />

Hence the DataContext of the grid is CurrentViewModel

In ReservationListingViewModel, the MakeReservationCommand set the CurrentViewModel to MakeReservationViewModel who contains the UserName property.

  • Related