简体   繁体   English

对Window中的UserControl中的DataContext感到困惑

[英]Confused about DataContext in UserControl from Window

I am confused about DataContext in an UserControl: 我对UserControl中的DataContext感到困惑:

I have created an UserControl with Textboxes etc... 我已经用文本框等创建了一个UserControl ...

In a wpf-window I have included this UserControl and the binding works as I want and expect. 在wpf窗口中,我包含了此UserControl,并且绑定可以按照我的期望和预期工作。

But If I write the following in the UserControl's constructor: 但是,如果我在UserControl的构造函数中编写以下代码:

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

the vm and the DataContext is always null. vm和DataContext始终为null。 How can I get the window's datacontext in my UserControl ? 如何在UserControl中获取窗口的数据上下文?

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

Thanks in advance 提前致谢

During the execution of the constructor the DataContext is not yet set. 在构造函数执行期间,尚未设置DataContext。 Move the assignement to a DataContextChanged event handler: 将分配移动到DataContextChanged事件处理程序:

public VehicleFields()
{
    InitializeComponent();

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

You can do this: 你可以这样做:

XAML: XAML:

<UserControl ...  DataContextChanged="VehicleFields_OnDataContextChanged">

Code begin: 代码开始:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM