我对UserControl中的DataContext感到困惑:
我创建了一个带文本框等的UserControl ......
在一个wpf窗口中,我已经包含了这个UserControl,并且绑定可以按照我想要和期望的方式工作。
但是如果我在UserControl的构造函数中编写以下内容:
public partial class VehicleFields : UserControl
{
VehicleAddEdit vm;
public VehicleFields()
{
InitializeComponent();
vm = this.DataContext as VehicleAddEdit;
}
}
vm和DataContext始终为null。如何在UserControl中获取窗口的datacontext?
窗口-XAML:
<Window x:Class="KraftSolution.Windows.Vehicle.VehicleAdd"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:UCs="clr-namespace:Test.UserControls"
xmlns:local="..."
>
<Window.Resources>
<local:VehicleAddWindow x:Key="VehicleAddWindow"/>
</ResourceDictionary>
</Window.Resources>
<Grid Name="MainGrid"
Style="{StaticResource DataManipulationGrid}"
DataContext="{StaticResource VehicleAddWindow}">
<UCs:VehicleFields/>
</Grid>
提前致谢
答案 0 :(得分:2)
在执行构造函数期间,尚未设置DataContext。将分配移动到DataContextChanged
事件处理程序:
public VehicleFields()
{
InitializeComponent();
DataContextChanged += (s, e) => vm = DataContext as VehicleAddEdit;
}
答案 1 :(得分:1)
你可以这样做:
XAML:
<UserControl ... DataContextChanged="VehicleFields_OnDataContextChanged">
代码开始:
private void VehicleFields_OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
vm = DataContext as VehicleAddEdit;
}