开发者

How to bind to a field without specifying Path or Datacontext?

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜