0

When a DataTemplateSelector is declared in an XAML Control's Resource (as below) how can it be supplied/bound to a runtime value that is not a member of the ItemsSource? For example it may require a service, datasource, configuration param e.t.c

Example: ref. "How Can This Be Supplied From The Data Context or Backing Code???"

<UserControl.Resources>
    <DataTemplate x:Key="StringDataTemplate">
            <TextBox Grid.Column="2" Text="{Binding Value}" />
    </DataTemplate>
    <DataTemplate x:Key="DateDataTemplate">
            <DatePicker Grid.Column="2" SelectedDate="{Binding Value}" />
    </DataTemplate>
    <local:MyDataTemplateSelector x:Key="templateSelector" 
          SomeRuntimeValue="How Can This Be Supplied From The Data Context or Backing Code???"
          StringDataTemplate="{StaticResource StringDataTemplate}"
          BooleanDataTemplate="{StaticResource BooleanDataTemplate}"/>
</UserControl.Resources>
<StackPanel>
    <ListBox ItemsSource="{Binding SomeDataCollection}"      
             Grid.IsSharedSizeScope="True" 
             HorizontalContentAlignment="Stretch"
             ItemTemplateSelector="{StaticResource templateSelector}"/>
</StackPanel>

Thanks in advance :)

Andrew
  • 33
  • 8

2 Answers2

1

I have used the following solution effectively, however I am not in a position to determine if this is the best solution or the other one hbarck has posted.

Pass Data to Data Template Selector

Community
  • 1
  • 1
Andrew
  • 33
  • 8
  • Using an attached property on the parent control and finding the parent control in the DataTemplateSelector as shown in the linked post seems more elegant to me, so +1. Unfortunately, this wouldn't work for validation, would it? – hbarck May 01 '13 at 07:51
0

You can do it as shown in this answer: Binding on a Non-UIElement

The problem basically is the same as in the other question: how can one use DataBinding on an object which isn't a DependencyObject or cannot inherit the DataContext because it is outside the visual tree?

Instead of creating a ValidationRule, obviously you'd have to create a DataTemplateSelector, though.

Community
  • 1
  • 1
hbarck
  • 2,934
  • 13
  • 16
  • Thanks hbarck, I tried this and it looked promising. The annoyance is adding additional classes that are just there to boilerplate. Consequently I opted for an alternative solution. Perhaps there is a reason for this, but it's disappointing that DataTemplateSelector's can not register DependencyProperties (or that DataTemplateSelector is not an interface). – Andrew May 01 '13 at 02:24
  • @Andrew: anyway, at least you can make those classes sufficiently reusable so that you can use them in other similar scenarios, couldn't you? – hbarck May 01 '13 at 07:53