c - 访问 View 中的 DataContext 属性

标签 c wpf mvvm

我希望有人能给我一个正确的方向,我目前正在学习 WPF 和 MVVM - 可以说它并不是一帆风顺。基本上,我试图访问 DataContext 的属性并将它们绑定(bind)到我 View 中的属性。老实说,我自己有点陷入困境。

当用户单击相关按钮时,它会触发下面的代码。

 private void OnReceiptClick(object sender, RoutedEventArgs e)
    {
        var dialogBox = new DisplayReceiptView(((CheckMemberViewModel) this.DataContext).ReceiptViewModel);
        dialogBox.ShowDialog();
    }

我的 CheckMemberViewModel 当前持有我想要的“Person”属性,并且在此阶段 DataContext 已按预期填充。

我的 DisplayReceiptView 背后的代码如下所示:

 public DisplayReceiptView(ReceiptViewModel context) : this()
    {
        this.DataContext = context;
    }

一切似乎再次正确,最后在我的 XAML 中我有了

<Grid DataContext="{Binding Path=Person}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition Width="150"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="10" />
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Label Grid.Column="1" Grid.Row="1">Name:</Label>
        <TextBox Grid.Column="2" Grid.Row="1" Text="{Binding Path=Person.Forename}"></TextBox>
      </Grid>

不幸的是,无论我做了什么,而且我认为我目前所处的位置是我所经历过的最接近的位置,数据似乎并没有绑定(bind)。下面是我的 ViewModel 属性代码

       private Person _person;
        public Person Person
    {
        get { return _person; }
        set
        {
            if (value != _person)
            {
                _person = value;
                OnPropertyChanged("Person");
            }
        }
    }

非常感谢任何帮助。

最佳答案

<TextBox Grid.Column="2" Grid.Row="1" Text="{Binding Path=Person.Forename}"></TextBox>

这是错误的,因为您已经绑定(bind)到 Person

<TextBox Grid.Column="2" Grid.Row="1" Text="{Binding Forename}"></TextBox>

这就是你所需要的

<TextBox Grid.Column="2" Grid.Row="1" Text="{Binding Forename, Mode=TwoWay}"></TextBox>

将保存对源的更改并检索更改,但当然您需要保存上下文更改以使其永久化

关于c - 访问 View 中的 DataContext 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25810951/

相关文章:

c++ - 按类型比较指针?

c# - 在代码隐藏中创建样式

c# - 将 ViewModel 连接到 Silverlight 中的 View

wpf - 在Catel MVVM WPF中使用TabControl时的性能

创建一个函数以从文件 : which approach would be more efficient? 创建数组

c - printf() 填充 C 中的列

WPF TopMost 控件

c# - 避免在每个 setter 中调用 RaisePropertyChanged

c++ - Int(1digit) 到 char 没有任何功能

c# - 使用 MVVM 的 DataTemplate ListBox 绑定(bind)和触发器中的 CheckBox