Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 470
Vaccano Avatar asked Dec 23 '09 15:12

Vaccano


1 Answers

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
        }
    }
}
like image 114
Heinzi Avatar answered Sep 19 '22 09:09

Heinzi