我希望有人能给我一个正确的方向,我目前正在学习 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/