Binding between Usercontrol with listbox and parent control (MVVM)

前端 未结 1 1669
离开以前
离开以前 2020-12-22 12:58

I have a UserControl which contains a listbox and few buttons.



        
1条回答
  •  情话喂你
    2020-12-22 13:08

    The ListBox in your UserControl isn't correctly binding to LBItems. The DataContext of the ListBox is not your control so it's trying to bind LBItems directly from your ViewModel.

    In your UserControl declaration add DataContext="{Binding RelativeSource={RelativeSource Self}}". That should correctly set your DataContext to the UserControl and allow you binding to correctly locate the LBItems property.

    Edit

    Your comment reminded me. You need to set the DataContext of your Grid to be your UserControl. The simplest way to do this is to name the Grid i.e. and then in the constructor for your UserControl LayoutRoot.DataContext = this;

    If you set the DataContext of the UserControl you break the bindings from your VM, but if you set them on the Grid the top bindings still work and all controls inside the UserControl can correctly bind to the UserControl.

    0 讨论(0)
提交回复
热议问题