OK。这是WPF,我试图将我的窗口绑定到ViewModel。虚拟机看起来是这样的:WPF绑定:绑定到DataContext的父代
public class VM
{
public SalesRecord SR {get; set;}
public List<string> AllSalesTypes {get; set;}
}
public class SalesRecord
{
public int ID {get; set;}
public DateTime Date {get; set;}
}
这里是我的XAML:
...
<TextBox Text="{Binding Path=ID, Mode=TwoWay}" />
<TextBox Text="{Binding Path=Date, Mode=TwoWay}" />
<ComboBox ItemsSource="{Binding AllSalesTypes}" Text="{Binding Path=SalesType, Mode=TwoWay}" />
...
我在运行时设置数据上下文的对象是这样的:
this.DataContext = _vm.SR;
现在结合表达式适用于指向SR
对象(例如ID
和Date
)的属性的所有我的TextBoxes
,bu t ComboBox
需要显示所有SalesType的列表不起作用,显然是因为AllSalesTypes
是类的成员。
我的问题是:有没有办法编写一个绑定表达式来查看当前DataContext
的父项而不是自身?
这是我已经写过的答案,但你的速度更快。但是...当您将DataContext设置为VM并使用Text =“{Binding SR.ID}”时,如果更改SR的某些属性,则不会引发PropertyChanged事件。如果要将这些更改传播到TextBox的Text属性,则必须提高它。但是是的:)拿起我的赞同:) – 2013-02-17 13:55:08
@ViktorLaCroix正确的,就像任何其他类你想在UI中看到变化 - SalesRecord也应该实现INotifyPropertyChanged – Blachshma 2013-02-17 14:22:04
是的......或者你可以RaisePropertyChanged(“SR”)在虚拟机...也工作:)和SalesRecord不必实施INotifyPropertyChanged – 2013-02-17 14:23:59