开发者

WPF DataContext Binding Not Occuring

开发者 https://www.devze.com 2023-02-14 16:12 出处:网络
I have a user control that embeds dynamically a number of other controls based on similar DataTemplates.

I have a user control that embeds dynamically a number of other controls based on similar DataTemplates.

My control has a ViewModel with bindable properties for both the DataContext of the hosted sub-control and the ContentTemplate. However, whe开发者_开发知识库n I run the template binds fine and initializes but the DataContext never gets picked up, even with a DataContextChanged event.

<ContentControl Name="SessionControl1" DataContext="{Binding SessionItem1}" ContentTemplate="{Binding Source={StaticResource ViewModel},Path=Session1Template}"  /> 

Now as a test, I took one of the switchable controls that I wanted (AudioCard.xaml) and tried using it in the same place directly like so:

<local:AudioCard DataContext="{Binding SessionItem1}" />

This works fine, the control initializes just like in the dynamic case AND the DataContextChanged event fires with the correct binding. This leads me to think that binding to the DataContext in the ContentControl is not working.

Two questions: 1) is there an easy way to fix it?

2) is there a better way to do it?

EDIT: Based on first answer, I changed the code to look like this:

<ContentControl Name="SessionControl1" Grid.Row="0" Grid.Column="0" ClipToBounds="False" Height="128" Width="128"
                                        DataContext="{Binding SessionItem1}"
                                        ContentTemplateSelector="{StaticResource ProximitySessionCardTemplateSelector}"  />

I can see the code going into my content template selector but my object in the selector is empty. Should I be binding to something else?


Ok, based on Elad's advice of using the data template selector in XAML and with the correct binding to Content instead of DataContext, this code works as desired:

<ContentControl Name="SessionControl1" 
            Content="{Binding Source={StaticResource ViewModel},Path=SessionItem1}"                                        
            ContentTemplateSelector="{StaticResource ProximitySessionCardTemplateSelector}"  />


As to Q2:

Why are you binding to ControlTemplate?

  1. You can simply create a DataTemplate that "catches" a specific type (the property in the ViewModel) and there fore will show a template based on the object you put inside automatically, without the need to bind ControlTemplate as well.

  2. If you're holding ControlTemplate property in your ViewModel (and it seems like you do), you're violated one of MVVM's most important rules - The ViewModel knows nothing about the View, and holds no references to Controls or UI what-so-ever.

0

精彩评论

暂无评论...
验证码 换一张
取 消