Question

I'm using a few data templates to display different values, those data templates are chosen by DataTemplateSelector. Every control has some DataBinding to my custom objects. Objects are part of an ObservableCollection and then DTS is choosing the template for them. The problem is: When I try to run my app with some pre defined objects (in code) the selected controls has no values. Ex:

  <!--Date Template-->
    <DataTemplate x:Key="DateTemplate">
        <WrapPanel x:Name="DateTemplate_Panel">
            <WrapPanel.DataContext>
                <params:FTParams />
            </WrapPanel.DataContext>
            <Label x:Name="DateTemplate_Label" Content="{Binding Path=Name}" />
            <DatePicker x:Name="DateTemplate_DatePicker" SelectedDate="{Binding Path=SelectedValue}" SelectedDateFormat="Long" />
        </WrapPanel>
    </DataTemplate>

Controls are responding only when I change their value (INotifyPropertyChanged is implemented)

If I set

<Label Content="{Binding Path=SelectedValue}"/> 

and I select a date in DataPicker then the content is loaded correctly. But I really need to have this values loaded on startup. Can you give me some advice?

Était-ce utile?

La solution

The data template should not have embedded data. And you definitely don't want to instantiate instances of FTParams, from within the DT. The DataContext property of the DataTemplate is set implicitly, when you have the data somewhere else in the tree.

I assume you have some sort of ItemsControl, but for the simplicity, let the sample below have a content control:

<ContentControl ContentTemplate="{StaticResource DateTemplate}">
    <params:FTParams />
</contentControl>

If you had all your items in ItemsControl (with ItemsSource bind to the ObservableCollection), then instead of ContentTemplate you should set the ItemsTemplate, or if you want to work with template selector, set the ItemTemplateSelector.

<ItemsControl ItemsSource="{Binding PathToTheObsCollectionProperty}"
    ItemTemplateSelector="{StaticResource MySelector}" />

In all cases, the DT should not have explicitly set the DataContext property.

Then have your data template without the DataContext element.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top