Reputation: 1089
I am confused about DataContext in an UserControl:
I have created an UserControl with Textboxes etc...
In a wpf-window I have included this UserControl and the binding works as I want and expect.
But If I write the following in the UserControl's constructor:
public partial class VehicleFields : UserControl
{
VehicleAddEdit vm;
public VehicleFields()
{
InitializeComponent();
vm = this.DataContext as VehicleAddEdit;
}
}
the vm and the DataContext is always null. How can I get the window's datacontext in my UserControl ?
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
Upvotes: 0
Views: 81
Reputation: 39326
You can do this:
XAML:
<UserControl ... DataContextChanged="VehicleFields_OnDataContextChanged">
Code begin:
private void VehicleFields_OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
vm = DataContext as VehicleAddEdit;
}
Upvotes: 1
Reputation: 128060
During the execution of the constructor the DataContext is not yet set. Move the assignement to a DataContextChanged
event handler:
public VehicleFields()
{
InitializeComponent();
DataContextChanged += (s, e) => vm = DataContext as VehicleAddEdit;
}
Upvotes: 2