Home > Back-end >  How to Binding data to User Control loaded in Control Template?
How to Binding data to User Control loaded in Control Template?

Time:04-23

My CMainViewModel has a property called AnalogGaugeValue1

On my Window I have a data template as shown below. I use this template to load a user control named AnalogIOView and try to binding the dependency property, GaugeValue1DP, inside AnalogIOView to the AnalogGaugeValue1

<Window>

  <Window.Resources>

    <DataTemplate x:Key="AnalogIOViewTemplate" DataType="{x:Type local:CMainViewModel}">
        <local:AnalogIOView 
               GaugeValue1DP="{Binding Path=AnalogGaugeValue1}"   />
   </DataTemplate>

  </Window.Resources>

<Window>

I use the ContentControl to load the AnalogIOViewTemplate in my Window as shown below

<Grid>

                        <ContentControl>
                            <ContentControl.Style>
                                <Style TargetType="{x:Type ContentControl}">
                                    <Setter Property="ContentTemplate" Value=" 
                                    {StaticResource AnalogIOViewTemplate }" />
                                </Style>
                            </ContentControl.Style>
                        </ContentControl>

</Grid>

The user control displays correctly on my Window but I could not set the Analog Gauge value through binding in CMainViewModel.

However, If I just load the user control directly (without using Control Template) then it is working correctly as shown below

<Grid>
   <local:AnalogIOView GaugeValue1DP="{Binding Path=AnalogGaugeValue1}" />
</Grid>

My question is why it does not work when loading the user control using Content Control template and data template

Thanks for your help

CodePudding user response:

You have to set the Content property, and it would also be simpler not set an x:Key on the DataTemplate. It would then automatically be selected as the ContentTemplate of the ContentControl.

<Window>
    <Window.Resources>
        <DataTemplate DataType="{x:Type local:CMainViewModel}">
            <local:AnalogIOView GaugeValue1DP="{Binding AnalogGaugeValue1}"/>
        </DataTemplate>
    </Window.Resources>

    <Grid>
        <ContentControl Content="{Binding}"/>
    </Grid>
<Window>
  • Related