I have problem with WPF – I’m quiet new in this smart technology. So the problem is:
I have a window. In this window’s resources I have stored an element – eg. a Grid with unique key (assume x:Key=”myGrid”). In this Grid I have a TextBox identified by a name (x:Name=”myTextBox”).
My Window contains only an empty Grid (named eg. winGrid). I programmatically set the myGrid as a child of the winGrid. And now, in runtime, I want to get a reference to the myTextBox object. I spent plenty of time googling, but nothing worked for me (FindName and similar methods).
Do you have please any idea, what I have to do to get the ball rolling?
Here is (pseudo)code snippet once more:
<Window x:Class="LoginForm.RidicWindow"
...>
<Window.Resources>
<Grid x:Key="myGrid">
<Border...
<Grid...
...
<TextBlock x:Name="myTextBlock" Grid.Column="0".../>
</Grid>
</Grid>
</Window.Resources>
<Grid x:Name="winGrid">
...
</Grid>
And now I set the myGrid as a child of winGrid:
(something like)
winGrid.Childrens.Clear();
winGrid.Childrens.Add((Grid)FindResource(myGrid));
And now I want to get a reference to myTextBlock, which is descendant of the myGrid.
I tried something like
((Grid)FindResource(myGrid)).FindByName("myTextBlock");
this, of course, doesn’t work.
Hope you understand me, what I want to get.
Lot of thanks!
You can not do this (By the way, you can, but it’s really bad, ugly and not recommended) The resources of a window to serve another purpose.
As mentioned, you must create a component (Usercontrol or other).. Although there are some other options for what you seek.
You can try some of what I wrote below:
1) Creating a custom component may be a UserControl, Grid or anything else…
and
2) A little more complicated:
and
In this option you will not have like a grid control to instantiate. (I see it often used in reports). You should create a .xaml and define it as a resource.
To find components you should look in the visual tree (as already responded)…
( How can I find WPF controls by name or type? )