2.在WPF中,很多控件拥有Name属性,例如上方我们应用Button的Name来设置Content,button.Content=button.Name。
是因为它们的父类FrameworkElement中都定义了Name属性,以下用SomeWpfType来庖代这些类型(便于表述)。
下面,我们不应用XAML和x:Name,应用Code-Behind和SomeWpfType.Name来测试一下。
namespace Cnblog
{
// 应用Button的Name属性
public class SetNameByCodeBehind : Window
{
public SetNameByCodeBehind()
{
// Buttons
var button1 = new Button { Name = "Button1" };
button1.Loaded += ButtonLoaded;
var button2 = new Button { Name = "Button2" };
button2.Loaded += ButtonLoaded;
// StackPanel
var contentPanel = new StackPanel();
contentPanel.Children.Add(button1);
contentPanel.Children.Add(button2);
// Window
this.Title = "Set Name By Code-Behind";
this.Height = 100;
this.Width = 300;
this.Content = contentPanel;
}