Come legare il contenuto di un controllo del WPF al DataContext del suo contenitore, quindi posso applicare un datatemplateselector in base a quell'oggetto?

StackOverflow https://stackoverflow.com/questions/5036835

  •  15-11-2019
  •  | 
  •  

Domanda

Sto cercando di associare una finestra WPF in cima a un viewModel che contiene due collezioni, A e B. Sto tentando di utilizzare DataTemplates per visualizzare A o B a seconda dell'impostazione di un flag nel mio viewModel.

.

A tal fine, ho impostato il DataContext = ViewModel della finestra.Tuttavia, quando tenta di tentare di associare un ContentControl a quel datacontext e applicare un DataTemplateSelector ad esso, il parametro item del metodo SelectTemplate(object item, DependencyObject container) del selettore è sempre nullo:

<Window [snip] Title="MainWindow">
    <Window.Resources>
        <!-- DataTemplate and Selector declarations -->
    </Window.Resources>
    <Grid>
        <ContentControl Content="{Binding}"              
                        ContentTemplateSelector="{StaticResource templateSelector}" />
    </Grid>    
</Window>
.

Come dovrebbe essere vincolante che ContentControl in modo tale che il ViewModel della finestra venga trasmesso al suo DataTemplateSelector?

È stato utile?

Soluzione

this worked for me:

<ContentControl Content="{Binding DataContext, RelativeSource={RelativeSource Self}}"              
                    ContentTemplateSelector="{StaticResource templateSelector}" />

Edit:

I agree with Aaron though, that this might not be the best way to accomplish things. You said you're using a ViewModel. The easiest way would probably be to bind your ItemsControl to a new "SelectedCollection" property on your Viewmodel that exposes the wanted collection. Then in your flag (assuming it is a property) you can fire propertychanged for "SelectedCollection".

Altri suggerimenti

Lots of things going on here...

You said you are using the DataTemplateSelector to either display collection A or collection B, while at the same time you stated you are setting one of the collections as the DataContext of the Window.

If you want to hide the data in one collection perform filtering on the collection itself. Another approach is to run the binding through an IValueConverter or IMultiValueConverter. Yet another solution could be to have two UI elements bound to each collection respectively and change the Visiblity of the UI element based on the value in your ViewModel.

Lot's of different options...and if I understand you correctly the DataTemplateSelector should not be one of them.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top