WPF DataTemplate - x:Key vs DataType="{x:Type XXXX")

Vaccano picture Vaccano · Dec 23, 2009 · Viewed 14.6k times · Source

I have a DataTemplate that I want to find using the FrameworkElement.FindResource(). To do that I need to have a key on the data template.

The problem is that x:key and assigning a data type are mutually exclusive. (Reference)

So, once I set the DataType for my template, how do I find the Key value? Is there some formula that converts the DataTemplate into a string for the Key?

(For inquries as to why I need to get the DataTemplate found by Resource see this question.

Answer

Heinzi picture Heinzi · Dec 23, 2009

The x:Key seems to be an object of type System.Windows.DataTemplateKey. So, you can "create" the key for your resource with new DataTemplateKey(typeof(myType)). FindResource will work with this key, since TemplateKey.Equals has been overridden.

Here is a very simple example application:

XAML:

<Window ...>
    <Window.Resources>
        <DataTemplate DataType="{x:Type TextBlock}">
        </DataTemplate>
    </Window.Resources>

    <Button Click="Button_Click">Test</Button>
</Window>

Codebehind:

//using ...

namespace WpfCsApplication1 {
    public partial class Window1 : Window {
        public Window1() {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e) {
            var key = new System.Windows.DataTemplateKey(typeof(TextBlock));
            var r = (DataTemplate)this.FindResource(key);

            MessageBox.Show(r.ToString()); // to show that it worked
        }
    }
}