Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Certificate and correct answer for the question

Tags:

wpf

I am preparing for an exam and studying questions. However I have one question which in my opinion the answer is wrong. Here's the question where the correct answer is D:

You use Microsoft .NET Framework 4 to create a Windows Presentation Foundation (WPF) application. The application has a window named MainWindow that has a StackPanel control named sp as the root element. You want to create a Button control that contains a TextBlock control with the "Save" Text property. You need to create the control dynamically and add the control to sp. Which code segment should you write in the constructor of the MainWindow class

A:

Button btn = new Button();
TextBlock text = new TextBlock();
text.Text = "Save";
btn.Content = text;
sp.DataContext = btn;

B:

Button btn = new Button();
TextBlock text = new TextBlock();
text.Text = "Save";
btn.Content = text;
sp.Children.Add(btn);

C:

Button btn = new Button();
TextBlock text = new TextBlock();
text.Text = "Save";
sp.Children.Add(btn);
sp.Children.Add(text);

D:

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

In my opinion the correct answer is B? Do you have any sugesstions?

like image 712
niao Avatar asked Mar 20 '11 13:03

niao


2 Answers

I think you're right. Answer D makes no sense at all, because:

  1. you don't need the ContentTemplateSelector, since you're defining the content explicitly
  2. ContentTemplateSelector shouldn't be used explicitly, it's used by ContentControl when it needs to render non-visual content
  3. ContentTemplateSelector is null by default, so the code in answer D would crash with a NullReferenceException
like image 88
Thomas Levesque Avatar answered Nov 15 '22 07:11

Thomas Levesque


I passed the same exam last week. And I agree that the correct answer should be B. You can try both in a sample application and you will see that D does not work.

like image 27
Jogy Avatar answered Nov 15 '22 08:11

Jogy