Window 对 UserControl 中的 DataContext 感到困惑

Confused about DataContext in UserControl from Window

我对 UserControl 中的 DataContext 感到困惑:

我创建了一个带有文本框等的用户控件...

在 wpf-window 中,我包含了这个 UserControl 并且绑定工作如我所愿。

但是如果我在 UserControl 的构造函数中编写以下内容:

public partial class VehicleFields : UserControl
{
    VehicleAddEdit vm;
    public VehicleFields()
    {
        InitializeComponent();
        vm = this.DataContext as VehicleAddEdit;
    }
 }

vm 和 DataContext 始终为空。如何在我的用户控件中获取 window 的数据上下文?

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

提前致谢

在构造函数执行期间,DataContext 尚未设置。将分配移动到 DataContextChanged 事件处理程序:

public VehicleFields()
{
    InitializeComponent();

    DataContextChanged += (s, e) => vm = DataContext as VehicleAddEdit;
}

你可以这样做:

XAML:

<UserControl ...  DataContextChanged="VehicleFields_OnDataContextChanged">

代码开始:

  private void VehicleFields_OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
  {
        vm = DataContext as VehicleAddEdit;
  }