证书和问题的正确答案

nia*_*iao 5 wpf

我正在准备考试和学习问题.但是我有一个问题,在我看来答案是错误的.这是正确答案是D的问题:

您使用Microsoft .NET Framework 4来创建Windows Presentation Foundation(WPF)应用程序.该应用程序有一个名为MainWindow的窗口,它有一个名为sp的StackPanel控件作为根元素.您想要创建一个Button控件,其中包含带有"Save"Text属性的TextBlock控件.您需要动态创建控件并将控件添加到sp.您应该在MainWindow类的构造函数中编写哪个代码段

A:

Button btn = new Button();
TextBlock text = new TextBlock();
text.Text = "Save";
btn.Content = text;
sp.DataContext = btn;
Run Code Online (Sandbox Code Playgroud)

B:

Button btn = new Button();
TextBlock text = new TextBlock();
text.Text = "Save";
btn.Content = text;
sp.Children.Add(btn);
Run Code Online (Sandbox Code Playgroud)

C:

Button btn = new Button();
TextBlock text = new TextBlock();
text.Text = "Save";
sp.Children.Add(btn);
sp.Children.Add(text);
Run Code Online (Sandbox Code Playgroud)

d:

Button btn = new Button();
TextBlock text = new TextBlock();
text.Text = "Save";
btn.ContentTemplateSelector.SelectTemplate(text, null);
sp.Children.Add(btn);
Run Code Online (Sandbox Code Playgroud)

在我看来,正确的答案是B?你有任何sugesstions?

Tho*_*que 7

我觉得你是对的.答案D完全没有意义,因为:

  1. 你不需要ContentTemplateSelector,因为你明确地定义了内容
  2. ContentTemplateSelector 不应该显式使用,ContentControl在需要呈现非可视内容时使用它
  3. ContentTemplateSelector 默认情况下为null,因此答案D中的代码将崩溃 NullReferenceException