<Window ...>
<Window.Resources>
<DataTemplate DataType="{x:Type TextBlock}">
</DataTemplate>
</Window.Resources>
<Button Click="Button_Click">Test</Button>
</Window>
代码后置文件:
//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
}
}
}
{x:Type ...}
作为键在 XAML 中引用它。 - Heinzi