简体   繁体   中英

DataContext is not Accessible in Event of User Control

I am seeking a solution for below situation

In my windows 10 app i have a order.xaml, inside that page i have a user control, i am successfully receiving the DataContext from order page in my user control. But when OrderItemList_Loaded event fires within my user control i dont receive DataContext in that case, it's null. How can i access the DataContext in case of event within user control?

Below is the code of User Control.

public sealed partial class OrderItemsUserControl : UserControl
{
    public OrderViewModel order
    {
        get { return this.DataContext as OrderViewModel; }
    }

    public OrderItemsUserControl()
    {
        this.InitializeComponent();
        this.DataContextChanged += (s, e) => Bindings.Update();
    }


    private void OrderItemList_Loaded(object sender, RoutedEventArgs e)
    {
        order.OrderItems.CollectionChanged += (s, args) => ScrollToBottom();
    }

    private void ScrollToBottom()
    {
        ListScrollViewer.Measure(ListScrollViewer.RenderSize);
        ListScrollViewer.ScrollToVerticalOffset(ListScrollViewer.ScrollableHeight);
    }
}

Since the UserControl appears to have a different dataContext than the View page, and you said "in datacontext i am getting OrderItems", then delete the method "public OrderViewModel order" and change code to get rid of order like:

private void OrderItemList_Loaded(object sender, RoutedEventArgs e)
    {
        OrderItems.CollectionChanged += (s, args) => ScrollToBottom();
    }

Assuming OrderItems is a valid reference declaredin this viewModel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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