Binding View and ViewModel on a DataGrid

2019-08-03 16:15发布

I'm using a View and ViewModel set on an already existing ViewModel. You could say that's the base with the second ViewModel placed on that.

When placing another ViewModel in the underlying ViewModel of MainViewModel (BrowseViewModel in this particular sample), the associated ViewModel does not show up.

Implementation as follows:

class MainViewModel : PropertyChangedBase
{
    private BrowseViewModel _BrowseViewModel= new BrowseViewModel();

    public BrowseViewModel BrowseViewModel
    {
        get { return _BrowseViewModel; }
        set
        {
            if (_BrowseViewModel== value) return;
            _BrowseViewModel= value;
            NotifyOfPropertyChange("BrowseViewModel");
        }
    }
}

class BrowseViewModel: PropertyChangedBase
{
    private ListingViewModel _ListingViewModel = new ListingViewModel();
    public ListingViewModel ListingViewModel
    {
        get { return ListingViewModel; }
        set
        {
            if (_ListingViewModel == value) return;
            _ListingViewModel = value;
            NotifyOfPropertyChange("ListingViewModel");
        }
    }
}

ListingViewModel...

(I clipped of the non-relevant code here)

Implementation in my markup (MainView):

<ContentControl x:Name="BrowseViewModel"/>

and in BrowseView:

<DataGrid.RowDetailsTemplate>
     <DataTemplate>
         <ContentControl x:Name="ListingViewModel"/>
      </DataTemplate>
</DataGrid.RowDetailsTemplate>

I experienced the exact same problem today when adding another ViewModel to an existing underlying ViewModel of the MainViewModel. If I dont have a underlying ViewModel and if I'm using the current MainViewModel, everything works appropriately.

Note: I told Caliburn to look for Views and their ViewModels at the previously named namespaces, that is no issue.

2条回答
闹够了就滚
2楼-- · 2019-08-03 16:43

It appears you're binding something to a DataGrid in BrowseView correct?

Declaring something like

<ContentControl x:Name="ListingViewModel"/>

is the shorthand version of declaring

<ContentControl cal:View.Model="{Binding ListingViewModel" />

Therefore I'm assuming (it's been a while since I've worked in WPF) that the DataContext in the RowDetailsTemplate is not BrowseViewModel but whatever you're binding to the DataGrid.

查看更多
老娘就宠你
3楼-- · 2019-08-03 16:48

try this...

<ContentControl cal:View.Context="BrowseView" cal:View.Model="BrowseViewModel" />

this should get your BrowseView and bind accordingly, since MainViewModel holds BrowseViewModel prop it should bind correctly. This assumes <ProjectName>.Views.BrowseView namespace and <ProjectName>.ViewModels.BrowseViewModel, likewise with ListingViewModel

查看更多
登录 后发表回答