Sean
Sean

Reputation:

How to get WPF xaml content by code on form C#

I design a form in WPF project. The xaml content is automatically generated based on the GUI I design (drag/drop,set position on GUI). How can I read/retreive the xaml content data by code in C# on form?

Upvotes: 2

Views: 4714

Answers (2)

Jobi Joy
Jobi Joy

Reputation: 50038

If you got your XAML content in a stream you can use XAMLReader like bellow XamlReader.Load(stream) as UIElement

Update : Looks like you are looking to get the control reference to the code behind? Just name it with x:Name and use that inside your C# file.

Upvotes: 0

Arjan Einbu
Arjan Einbu

Reputation: 13692

In WPF you have to decide what controls/UI elements are accessible in codebehind/C# by adding the Name="someMeaningfullName" or x:Name="someMeaningfullName" to the element in XAML. Then you can access it in the codebehind like this: someMeaningfullName.Text = "blablabla";or similar.

The XAML:

<TextBox Name="_myTextBox" />
<!-- use x:Name if the element doesn't define the Name attribute -->

The codebehind:

string answer = _myTextBox.Text;
myTextBox.Text = "";

(By default, XAML elements are not represented by a member variable/field, as they would be in Windows Forms or ASP.NET)

Upvotes: 1

Related Questions