Passing data to the data template selector

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

The only thing I can think of is to use an attached property in the 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 cannot get the parameter value in the SelectTemplate method.

Any suggestion will be appreciated. Thanks in advance.

+3
source share
3 answers

Bypass

  • Use an attached property and a private static variable

  • Go through the visual tree doc.OfParentType <>

0
source

This is a little easier. In the handler:

SelectTemplate(object item, DependencyObject container)

. , UserControl, DataContext. :

public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
    var _Container = Library.TreeHelper.TryFindParent<MyUserControl>(container);

: http://www.hardcodet.net/2009/06/finding-elements-in-wpf-tree-both-ways

+3

A common solution is to use the properties of the item parameter to obtain the necessary information to select the correct template.

If you have a ViewModel , it may contain the necessary data.

0
source

Source: https://habr.com/ru/post/1737186/


All Articles