xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Wpf180706"
Title="Window11" Height="300" Width="300">
<Window.Resources>
<local:Person x:Key="person" Id="1" Name="zhangsan" Skill="wpf"></local:Person>
<DataTemplate x:Key="tpl">
<Border BorderBrush="Orange" BorderThickness="3" CornerRadius="5">
<StackPanel>
<TextBlock Text="{Binding Id}"></TextBlock>
<TextBlock Name="tb2" Text="{Binding Name}"></TextBlock>
<TextBlock Text="{Binding Skill}"></TextBlock>
</StackPanel>
</Border>
</DataTemplate>
</Window.Resources>
<Grid>
<StackPanel>
<ContentPresenter Name="cp" Content="{StaticResource person}" ContentTemplate="{StaticResource tpl}"></ContentPresenter>
<Button Click="btn_Click">btn</Button>
</StackPanel>
</Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Wpf180706
{
/// <summary>
/// Interaction logic for Window11.xaml
/// </summary>
public partial class Window11 : Window
{
public Window11()
{
InitializeComponent();
}
private void btn_Click(object sender, RoutedEventArgs e)
{
TextBlock tb = (TextBlock)this.cp.ContentTemplate.FindName("tb2", this.cp);
MessageBox.Show(tb.Text);
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Skill { get; set; }
}
}