简体   繁体   English

如何在WPF中的DataTemplateSelector类中查找UserControl中的资源?

[英]How to find a resource in a UserControl from a DataTemplateSelector class in WPF?

I'm creating my own UserControl and I have two different DataTemplates under the UserControl.Resources section in my XAML. 我正在创建自己的UserControl,并且在我的XAML中的UserControl.Resources部分下有两个不同的DataTemplates。 I want to choose between these two datatemplates depending on the value of a property on objects displayed in a listview. 我想在这两个datatemplates之间进行选择,具体取决于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. 我这样做是通过创建一个自定义DataTemplateSelector类并重写SelectTemplate方法,该方法应该返回我想要使用的DataTemplate。 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 . 但是,我不知道如何“查找”位于UserControls资源部分的数据模板,我看到的所有示例只从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?: 在这个例子中,他们获取当前的MainWindow然后使用FindResource来查找DataTemplate ,我如何以类似的方式获取我的UserControl ?:


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 上面的示例来自此处: ItemsControl.ItemTemplateSelector属性

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;
    }

I usually instantiate my DataTemplateSelector from code behind with the UserControl as parameter in the constructor of the DataTemplateSelector, like so: 我通常使用DataConmplateSelector的构造函数中的UserControl作为参数从后面的代码实例化我的DataTemplateSelector,如下所示:

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! 希望这可以帮助!

       <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! 仅限XAML!

A WinRT & Windows Phone solution involves moving up the visual tree until the parent control is found: WinRT和Windows Phone解决方案涉及向上移动可视树,直到找到父控件:

    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? FindParent方法基于这里接受的答案: 如何从ListViewItem获取ListView?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM