そのオブジェクトに基づいてDataTemplateseLectorを適用できるように、WPFコントロールのコンテンツをコンテナのDataContextにバインドする方法を教えてください。

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

  •  15-11-2019
  •  | 
  •  

質問

2つのコレクションを含むViewModelのATOPにWPFウィンドウをバインドしようとしています.BiewModelのフラグの設定に応じて、AまたはBのどちらかを表示するにはDataTemplatesを使用しようとしています。

その終了時には、ウィンドウのDataContext = ViewModelを設定しました。ただし、ContentControlをそのDataContextにバインドしてDataTemplateSelectorを適用しようとすると、セレクタのitemメソッドのSelectTemplate(object item, DependencyObject container)パラメータは常にNULLです。

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

ウィンドウのViewModelがContentControlに渡されるようにDataTemplateSelectorをどのように拘束するか。

役に立ちましたか?

解決

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".

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top