How to find a resource in a UserControl from a Dat

2019-04-09 00:42发布

问题:

I'm creating my own UserControl and I have two different DataTemplates under the UserControl.Resources section in my XAML. I want to choose between these two datatemplates depending on the value of a property on objects displayed in a listview. I do this by creating a custom DataTemplateSelector class and overriding the SelectTemplate method which is supposed to return the DataTemplate I wish to use. However, I have no idea how to "find" my datatemplates that are located in the UserControls resource section, all the examples I've seen only fetches datatemplates from Window.Resources. In this example they fetch the current MainWindow and then use FindResource to find the DataTemplate, how do I fetch my UserControl in a similar manner?:


public override DataTemplate 
            SelectTemplate(object item, DependencyObject container)
        {
            if (item != null && item is AuctionItem)
            {
                AuctionItem auctionItem = item as AuctionItem;
                Window window = Application.Current.MainWindow;

                switch (auctionItem.SpecialFeatures)
                {
                    case SpecialFeatures.None:
                        return 
                            window.FindResource("AuctionItem_None") 
                            as DataTemplate;
                    case SpecialFeatures.Color:
                        return 
                            window.FindResource("AuctionItem_Color") 
                            as DataTemplate;
                }
            }

            return null;
        }

The example above is from here: ItemsControl.ItemTemplateSelector Property

回答1:

I usually instantiate my DataTemplateSelector from code behind with the UserControl as parameter in the constructor of the DataTemplateSelector, like so:

public class MyUserControl : UserControl
{
    public MyUserControl()
    {
        Resources["MyDataTemplateSelector"] = new MyDataTemplateSelector(this);
        InitializeComponent();
    }
}

public class MyDataTemplateSelector : DataTemplateSelector
{
    private MyUserControl parent;
    public MyDataTemplateSelector(MyUserControl parent)
    {
        this.parent = parent;
    }

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        parent.DoStuff();
    }
}

Not the most prettiest girl in town, but it get the job done ;)

Hope this helps!



回答2:

Try this:

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        if (item != null && item is AuctionItem)
        {
            AuctionItem auctionItem = item as AuctionItem;

            switch (auctionItem.SpecialFeatures)
            {
                case SpecialFeatures.None:
                    return 
                        ((FrameworkElement)container).FindResource("AuctionItem_None") 
                        as DataTemplate;
                case SpecialFeatures.Color:
                    return 
                        ((FrameworkElement)container).FindResource("AuctionItem_Color") 
                        as DataTemplate;
            }
        }

        return null;
    }


回答3:

       <DataTemplate x:Key="addTemplate">
        <Button Command="{Binding Path=AddCommand}">Add</Button>
    </DataTemplate>

    <DataTemplate x:Key="editTemplate">
        <Button Command="{Binding Path=UpdateCommand}">Update</Button>
    </DataTemplate>

    <TemplateSelectors:AddEditTemplateSelector
        AddTemplate="{StaticResource addTemplate}"
        EditTemplate="{StaticResource editTemplate}"
        x:Key="addEditTemplateSelector" />

XAML only!



回答4:

A WinRT & Windows Phone solution involves moving up the visual tree until the parent control is found:

    protected override Windows.UI.Xaml.DataTemplate SelectTemplateCore(object item, Windows.UI.Xaml.DependencyObject container)
    {
        var parent = FindParent<MyParentControlType>(container as FrameworkElement);

        if(parent != null)
        {
            if (item is Something)
                return parent.Resources["TemplateForSomething"] as DataTemplate;
            else if(item is SomethingElse)
                return parent.Resources["TemplateForSomethingElse"] as DataTemplate;
            else 
                // etc
        }
        else
        {
            return App.Current.Resources["SomeFallbackResource"] as DataTemplate;
        }
    }

    public static T FindParent<T>(FrameworkElement element) where T : FrameworkElement
    {
        FrameworkElement parent = Windows.UI.Xaml.Media.VisualTreeHelper.GetParent(element) as FrameworkElement;

        while (parent != null)
        {
            T correctlyTyped = parent as T;

            if (correctlyTyped != null)
                return correctlyTyped;
            else
                return FindParent<T>(parent);
        }

        return null;
    }

The FindParent method is based on the accepted answer here: How to get a ListView from a ListViewItem?