tags:

views:

428

answers:

2

How do you guys pass the data (parameter) to DataTemplate Selector?

The only one that I can think of is to use an attached property in DataTemplate Selector?

Example:

public class DisableWeekendsSelection : DataTemplateSelector
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible", Justification = "DependencyProperty")]
        public static readonly DependencyProperty Parameter =
           DependencyProperty.RegisterAttached("Parameter", typeof(ObservableCollection<Date>), typeof(DisableWeekendsSelection),
           new FrameworkPropertyMetadata(null,
               FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

        public static ObservableCollection<Date> GetParameter(DependencyObject dp)
        {
            return dp.GetValue(Parameter) as ObservableCollection<Date>;            
        }

        public static void SetParameter(DependencyObject dp, ObservableCollection<Date> value)
        {            
            dp.SetValue(Parameter, value);
        }

        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {

The problem with this approach is that I'm not able to get the value of Parameter in SelectTemplate method.

Any suggestion would be appreciated. Thanks in advance.

A: 

The usual solution is to use the properties of the item parameter to get the needed info to choose the right template.

If you have a ViewModel, it can include the necessary data.

Timores
I have Date property and Holidays Property. DatePicker is binded with Date. I need to highlight holidays in Calender of DatePicker. That's why Im trying to pass the Holidays of VM to Data Template Selector.
Michael Sync
I always get null if I put this line var dates = container.GetValue(Parameter) as ObservableCollection<Date>; in SelectTemplate. :(
Michael Sync
Could you show how you set up the data template selector ?
Timores
DayTemplateSelector="{StaticResource disableHolidaySelection}" in telerik:RadDatePicker.. we have <my:DisableHolidaySelection.DefaultTemplate> and <my:DisableHolidaySelection.SpecialDay> in resource.. Example: http://www.telerik.com/community/forums/wpf/calendar/selectors-and-special-dates.aspx#1127883
Michael Sync
I managed to make it work by using an attached property and static variable.. but i dont think it's not good solution to use static variable so i'm seeking the suggestion from you guys..
Michael Sync
Sorry, I installed the RadControls and tried to find a solution, but could not succeed.
Timores
A: 

Workarounds

  1. Use the attached property and private static variable

  2. Walk the Visual Tree doc.OfParentType<>

Michael Sync