【问题标题】:How to bind to a field without specifying Path or Datacontext?如何在不指定路径或数据上下文的情况下绑定到字段?
【发布时间】:2022-12-18 12:26:11
【问题描述】:

我是 WPF 的新手,通过阅读书籍来收集知识。到目前为止,在所有书籍示例中,我都看到我们需要指定 ElementName + Path 或具有用于绑定的 DataContext。

但是在Youtube tutorial(和Source Code at GIT中,UI元素直接绑定到字段上,没有指定任何DataContext。例如下面的代码sn-p中,TextBoxText属性已经被绑定到 Username 而不指定任何 DataContext 或路径:

    <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>

问题:上面的绑定是如何工作的? Binding 如何知道指定了哪个UsernameHere is the link to the complete source code of the MakeReservatoonView.xaml

【问题讨论】:

  • 阅读Data binding overview。您对“ElementName+Path”与“DataContext”的理解是错误的。 Text="{Binding Username}" 仅适用于引用具有公共用户名属性的对象的 DataContext。但是,DataContext 值可以通过依赖属性值继承从父元素继承。
  • 您提供的代码不完整。在哪里定义属性用户名?构造函数中可能有一个数据上下文绑定(代码隐藏)。
  • 如果正在使用绑定,将定义一个DataContext。如果它未在 XAML 文件中声明,则它很可能位于关联的代码隐藏文件中。
  • @Jake:完整的代码很大,我已经提供了完整源代码的GitHub URL。
  • @Clemens 我知道 DataContext 值可以从父级继承,但是如果您打开完整的 XAML 文件(提供的 Github 链接),则没有指定 DataContext。但是根据下面 Orace 的回答,我知道 DataContext 在 CurrentViewModel 级别只指定了一次。

标签: c# wpf


【解决方案1】:

在 App.xaml.cs 中,您可以看到 MainWindow DataContext 设置为 MainViewModel
在 MainWindow 中,你有

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

因此网格的 DataContext 是 CurrentViewModel

在 ReservationListingViewModel 中,MakeReservationCommand 将 CurrentViewModel 设置为包含 UserName 属性的 MakeReservationViewModel。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 2012-11-30
    相关资源
    最近更新 更多