Cannot access TextBox in MainWindow.xaml.cs, which is UserControl

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 33183 Views - Last Post: 24 March 2013 - 09:07 AM Rate Topic: -----

#1 johnyjj2   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 42
  • Joined: 24-July 09

Cannot access TextBox in MainWindow.xaml.cs, which is UserControl

Posted 23 March 2013 - 09:55 AM

Hello,

I cannot access TextBox in Mainwindow.xaml.cs, which is part of UserControl.

The error I get:

Quote

Error 1 The name 'MyTextBox' does not exist in the current context H:\Projekty\WpfTest2\WpfTest2\Mainwindow.xaml.cs 26 4 WpfTest2


Mainwindow.xaml

<Window x:Class="WpfTest2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
		xmlns:local="clr-namespace:WpfTest2"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
		<Grid.ColumnDefinitions>
			<ColumnDefinition/>
		</Grid.ColumnDefinitions>
		<Grid.RowDefinitions>
			<RowDefinition/>
		</Grid.RowDefinitions>

		<TabControl>
			<TabItem Header="Test scenario" Name="TestScenarioTab">
				<local:TestScenario/>
			</TabItem>
		</TabControl>
	</Grid>
</Window>


TestScenario.xaml

<UserControl x:Class="WpfTest2.TestScenario"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
		<TextBox Name="MyTextBox">abcd</TextBox>
	</Grid>
</UserControl>


Mainwindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfTest2
{
	/// <summary>
	/// Interaction logic for Mainwindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		public MainWindow()
		{
			InitializeComponent();

			MyTextBox.Text = "asdf"; // ERROR!
		}
	}
}


How can I access TextBox? Please refer to the project attached (with the same code as above).

Best regards!

Is This A Good Question/Topic? 0
  • +

Replies To: Cannot access TextBox in MainWindow.xaml.cs, which is UserControl

#2 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Cannot access TextBox in MainWindow.xaml.cs, which is UserControl

Posted 23 March 2013 - 10:00 AM

You don't. This is a very bad way to do things.

You bind XML gui components to properties. That's the way WPF is meant to work.
So make a property and you can bind as many GUI controls to it as you like.
But for Pete's sake don't do this stuff of directly updating the text like this. Even if it is in your window.
26            MyTextBox.Text = "asdf"; // ERROR!



If you are trying to update a UserControl you DO NOT try to access the GUI components directly. EVER. You update a property of the UserControl. Then let the UserControl take care of its own reaction to that - such as a binding between the property and the TextBox.
Was This Post Helpful? 1
  • +
  • -

#3 johnyjj2   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 42
  • Joined: 24-July 09

Re: Cannot access TextBox in MainWindow.xaml.cs, which is UserControl

Posted 23 March 2013 - 10:14 AM

Hello,

thanks for your reply!

How am I supposed to do it? In reality, my problem is a little bit more complex, because I need to use in real project:
dgrNumericalParameters.ItemsSource = myTestClass.NumericalParameters;

Where:

Quote

The name 'dgrNumericalParameters' does not exist in the current context.

And my binding is as follows:
<DataGrid Grid.Row="8" Grid.Column="0" Margin="5" Grid.ColumnSpan="3" Name="dgrNumericalParameters" ItemsSource="{Binding TestScenarioClass}" />


In the test project I try the following:
<TextBox Name="MyTextBox" Text="{Binding Path=MyTextBoxBind}" />

But accessing it is still impossible:
MyTextBoxBind = "asdf"; // ERROR!

Even if I use TestScenario directly:
TestScenario.MyTextBoxBind = "asdf"; // ERROR!


I am rather new to WPF.

Best regards!
Was This Post Helpful? 0
  • +
  • -

#4 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Cannot access TextBox in MainWindow.xaml.cs, which is UserControl

Posted 23 March 2013 - 10:26 AM

It looks like you're rather new to C# too - sorry.
Its not working in your TestScenario case because the access for the GUI control is private not public.


Let's start with this question: Are you even familiar with Properties and Objects? If these are unfamiliar to you then you NEED to stop right here and work the two tutorials linked in my signature block. Properties and Classes are foundation concepts that you can't skip and come back to later. Everything else pretty much requires you grasp these.

I've been meaning to do a little sample/tutorial for WPF - at least to get people started. Hang out for an hour. Do those tutorials I pointed you at. And I'll run up a quick example and post it.
Was This Post Helpful? 1
  • +
  • -

#5 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Cannot access TextBox in MainWindow.xaml.cs, which is UserControl

Posted 23 March 2013 - 11:04 AM

I don't like my tutorials to look like crap. So here is a sneak peek at something I hastily threw together so you have a sample. I'll clean it up on my days off to be a proper tutorial.

Make a new WPF project titled "WpfOneOhOne".
Now you can just copy/paste the code below to your MainWindows.XML replacing all the existing code.
Spoiler


Make a new UserControl called PersonData
Again just copy/replace all of the XAML with this
Spoiler


In the C# code-behind for the Mainwindow.xaml.cs, copy/replace with this code:
Spoiler


In the PersonData.xaml.cs, copy/replace all the code with this:
Spoiler


This will give you a very simple Windows with a very simple UserControl. Notice that as you type in the TextBox of the UserControl the TextBlock (yellow) of the MainWindow is updating in real time.

Attached Image

The key points here is that nothing is directly accessing the .Text property of anything else.
Binding is used to related GUI controls to properties.
You can see how ElementName and Path relate to the instance of the UserControl and property of that instance.
Was This Post Helpful? 2
  • +
  • -

#6 johnyjj2   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 42
  • Joined: 24-July 09

Re: Cannot access TextBox in MainWindow.xaml.cs, which is UserControl

Posted 23 March 2013 - 01:13 PM

Thanks for reply,

I have read your tutorial about properties because I really lack understanding of that topic but I am (or at least I think I am :)) familiar with most of the things covered in tutorial about OOP.

What I lack is understanding of, let's say, skeleton WPF application in C#. I mean, when I create my own classes, I know what is inside those and how they depend on each other. However in C#.NET everything (or almost everything) is treated as classes. For example, I've heard that Bool is not really a type of variable but object. However, my knowledge didn't go much further.

When I have started working on my application, I have decided to focus on creating good architecture of that software from the very beginning, so that's why I still try to learn about this all stuff. I also would like to use WPF and Entity Framework, which I am not quite familiar with. (I have been creating apps in Win Forms for a longer time; even if I spend most of my time in TCL language).

I have MainWindow with its xaml and xaml.cs. I also have several additional files, one with abstract class, the other with classes derived from it. I also have UserControls included in Mainwindow.xaml so that I don't have the whole xaml in one large file. The data I need to handle is rather complex - I need to use lists of objects, which belong to classes that have some variables and other lists of different objects (at first I thought about structures but I have found out that I cannot bind structres to DataGrid).

But when it comes to how different files, connected with GUI (xaml.cs vs xaml), classes (from different files) depend on each other, it looks like it would be easier for me to put everything in one large file so that I don't care about different namespaces, everything is visible to everything and so on. But that would lead to a mess later. That would be even easier for me to use Windows Forms and not care about any databases (just to use some csv files) - but that would lead to even worse software architectures. So I have decided to rething the whole architecture from the very beginning. And that's the only way to learn something new and useful.

For example, in your second tutorial (about properties) I have found that you use RaisePropertyChanged, PropertyChanged and PropertyChangedEventArgs. I see that you write code of RaisePropertyChanged. But I cannot see where PropertyChanged and PropertyChangedEventArgs come from. I assume it is somehow connected with INotifyPropertyChanged but again, like with that skeleton C#.NET WPF app, it's using something I have not created, namespaces and classes I have not created and it becomes something I need to learn about.

You also use "e:" in line 45, that's the other thing I don't quite get. Or the fact that you create "private int _Age = 0" and then "public int Age". Why cannot you use only the latter? OK, I get that _Age is private for MainWindow class and "public int Age" is public (public to what, outside MainWindow class, in all the other classes that belong to "namespace DicTutorial"?).

In C++ I may simply use "public:" and write several variables (like "int myNumber", "bool myBool" and so on). Here it becomes more complex, I need to use both "private int _Age" and "public int Age". So if I have many variables, I need to write every single variable twice, as private and public, instead of only once (or more probably I don't understand something). And I cannot use "public:" as in C++ so it makes code more complex (unnecessarily?).

Do I have to use INotifyPropertyChanged after all, or is there any other way of achieving similar goal?

You say that "Its not working in your TestScenario case because the access for the GUI control is private not public". OK, I (hope I) understand it. But I've heard that it's not good to mess with auto-generated code and I guess I would need to change private to public in that auto-generated code. I can imagine that it may lead to many unnecessary problems so perhaps it's not the best thing I can do.

I will have a look at the code from your last reply in a moment.

Best regards!
Was This Post Helpful? 0
  • +
  • -

#7 johnyjj2   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 42
  • Joined: 24-July 09

Re: Cannot access TextBox in MainWindow.xaml.cs, which is UserControl

Posted 23 March 2013 - 01:27 PM

PS Surprisingly due to this error:

Quote

Error 1 ''<', hexadecimal value 0x3C, is an invalid attribute character. Line 4, position 55.' XML is not valid. H:\Projekty\WpfOneOhOne\WpfOneOhOne\PersonData.xaml 4 55 WpfOneOhOne


I had to replace line with this

xmlns:d="http://schemas.microsoft.com/exp&lt;b>&lt;/b>ression/blend/2008"

Was This Post Helpful? 0
  • +
  • -

#8 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Cannot access TextBox in MainWindow.xaml.cs, which is UserControl

Posted 23 March 2013 - 01:49 PM

Quote

it looks like it would be easier for me to put everything in one large file so that I don't care about different namespaces, everything is visible to everything and so on.


Different files doesn't mean different namespaces.
DO NOT put everything in one big file. You want to work in the opposite direction. Each *thing* goes in its own file. It makes maintenance and organization much easier and cleaner. Some people go so far as every enum in its own file. I put associated enums in one file because most are only a few lines long. But they are grouped together in a logical way based on need. Like Baud, Parity, Handshake enums are all in a file of SerialPortEnums.

Quote

For example, in your second tutorial (about properties) I have found that you use RaisePropertyChanged, PropertyChanged and PropertyChangedEventArgs. I see that you write code of RaisePropertyChanged. But I cannot see where PropertyChanged and PropertyChangedEventArgs come from.

They come from the .NET framework. Just hover your mouse over them and the IDE will provide their namespace in the ToolTip
Attached Image

Think of it this way. You use Button.Click all the time, but you didn't write the code for the Button or the code for the .Click event or the EventArgs that you see in all your method handlers. They come from the .NET framework. PropertyChanged is no different.


Quote

Or the fact that you create "private int _Age = 0" and then "public int Age". Why cannot you use only the latter?

_Age is the private backing field for the public property Age. This is common style. You have to have a backing field if you do more than {get; set;} in the property. This is explained in detail in the properties tutorial.

Quote

Do I have to use INotifyPropertyChanged after all, or is there any other way of achieving similar goal?

You need to use this interface. It is the interface that the provides the rest of the classes notification that the property has changed. When the property values changes, the subscribers are notified and can react. When the Age changes from 45 to 46, the TextBox is notified and updates the display on the GUI.

Quote

In C++ I may simply use "public:" and write several variables (like "int myNumber", "bool myBool" and so on). Here it becomes more complex, I need to use both "private int _Age" and "public int Age". So if I have many variables, I need to write every single variable twice, as private and public, instead of only once (or more probably I don't understand something). And I cannot use "public:" as in C++ so it makes code more complex (unnecessarily?).

Build a bridge and get over it. This isn't C++. You are mixing up simple fields with properties which are much more powerful.


Quote

You say that "Its not working in your TestScenario case because the access for the GUI control is private not public". OK, I (hope I) understand it. But I've heard that it's not good to mess with auto-generated code and I guess I would need to change private to public in that auto-generated code. I can imagine that it may lead to many unnecessary problems so perhaps it's not the best thing I can do.

Right. That's why you don't do it. Like I said, you do not do those things. You bind to properties. You say you want to code this stuff correctly from the start. Good. Then accept this. You do not go reaching into the individual GUI components of one class (a UserControl for example) from another class (the MainWindows in this case). Period. You don't do it. Bad programmer, no M&M's. You say you've been doing WinForms for a while. But these are foundation concepts for C# classes and not WinForms or WPF specifically. If you were doing it in WinForm, then you were wrong for doing it then and now you have a bad habit to un-learn.

Quote

However in C#.NET everything (or almost everything) is treated as classes.

Right. It is an Object Oriented language and programming paradigm. Classes are objects. Its all about objects which are just instantied classes. Classes are the blueprint. Objects are the things made based on the blueprints that you can use and interact with.


Quote

I have MainWindow with its xaml and xaml.cs. I also have several additional files, one with abstract class, the other with classes derived from it. I also have UserControls included in Mainwindow.xaml so that I don't have the whole xaml in one large file. The data I need to handle is rather complex - I need to use lists of objects, which belong to classes that have some variables and other lists of different objects (at first I thought about structures but I have found out that I cannot bind structres to DataGrid).

I think you're starting off too big. You are lacking a lot of solid comprehension for classes and properties. Making a big project like you've described before learning these foundation principals is just going to make things more confusing. Start small. Learn one concept at a time. Make a small R&D project like the UserControl code I gave you to just work on properties and bindings. Then work on just one object. Get where you really understand them and are not reaching several layers deep into them from external classes. Work on architecting your solutions. I'm worried when you suggest keeping everything in just one or two really big code files. If you can't organize the code, and be comfortable with logical breakdown of that, then you simply aren't ready to try to comprehend large amounts of complex data that you described. You'll get there. But you aren't there yet.

This post has been edited by tlhIn`toq: 23 March 2013 - 01:59 PM

Was This Post Helpful? 1
  • +
  • -

#9 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Cannot access TextBox in MainWindow.xaml.cs, which is UserControl

Posted 23 March 2013 - 02:01 PM

View Postjohnyjj2, on 23 March 2013 - 02:27 PM, said:

PS Surprisingly due to this error:

Quote

Error 1 ''<', hexadecimal value 0x3C, is an invalid attribute character. Line 4, position 55.' XML is not valid. H:\Projekty\WpfOneOhOne\WpfOneOhOne\PersonData.xaml 4 55 WpfOneOhOne


I had to replace line with this

xmlns:d="http://schemas.microsoft.com/exp&lt;b>&lt;/b>ression/blend/2008"


Notice the screw up there too? That's the web site's code parser trying to be helpful and thinking the 'b' is the start of a bold tag. Sometimes we just have to use our common sense and fix things, like you did. Well done.
Was This Post Helpful? 1
  • +
  • -

#10 johnyjj2   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 42
  • Joined: 24-July 09

Re: Cannot access TextBox in MainWindow.xaml.cs, which is UserControl

Posted 23 March 2013 - 04:25 PM

Thanks a lot! I really appreciate your help.

I have analyzed your code and what I can see is described below.

Deleting this part of code does not change application's behaviour:

<TextBox MinWidth="100"
	Margin="0,0,15,0"
	VerticalAlignment="Center"
	Text="{Binding ElementName=thisUC,
		Path=NameFirst,
		Mode=TwoWay,
		UpdateSourceTrigger=PropertyChanged}"
	>
</TextBox>


Name thisUC is used in Mainwindow.xaml

<Window x:Class="WpfOneOhOne.MainWindow"
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
	xmlns:WpfOneOhOne="clr-namespace:WpfOneOhOne"
	x:Name="thisUC"


And PersonData is User Control, not Mainwindow. Code x:Name="thisUC" is used inside main tag in MainWindow so it suggests me that MainWindow is UserControl, while it is not, it only uses UserControl. It confuses me a little bit.

I have created some breakpoints and noticed code's behaviour. It never enters Mainwindow.xaml.cs so it looks like something is happening outside my sight. After writing single letter in TextBlock, it also enters get and set of SharedString twice, while I could think it should happen only once. Or it simply jumps from one part of code to the other in more complex way due to using threads (as there is using System.Threading.Tasks;) and events.

I also have some small remarks about code's readability (or maybe I'm just picking holes in something good) - just because you want to make tutorial from this so that more people can benefit from this explanation. Wouldn't it be easier to read it if both cs files have similar order of parts of code? I mean, InitializeComponent() is first in PersonData.xaml.cs and much later in Mainwindow.xaml.cs. Similarly, RaisePropertyChangd() is at the end of MainWindow and in the middle of PersonData.

I always thought that it is easier to analyze something if it can be shown on the screen as a whole, without need to use scrollbars. (Similarly as with books, if some plot or picture is on the other side of a sheet of paper than description, one needs to change the page to see description, then change it to see the picture again and again).

I understand that using #region splits code into logical parts, but it's a little bit more difficult to find something in the code if inside the region there is only short piece of code and there are many regions in short piece of code (and it cannot be shown on the screen as a whole if I don't have large screen, but only laptop). Is there any way to easily highlight every region in Visual Studio (I use 2010)? I mean, something like using one color as background for one region, the other as background for the other region? Perhaps not. But that's the other minor remark, far away from main topic.

There are also many using statements. Are they all really necessary for such a small application?

Back to main topic, as I guess I will need to use the same thing, explained in this tutorial, many times in the application. I try to understand what is happening from the beginning (I write letter in TextBlock and it raises set in SharedString) to the end (set in NameFirst).

When exactly is PropertyChanged event raised? Is it just before using set of SharedString or just after? Is this order correct: PropertyChanged is raised automatically as event, then SharedString uses its set, then it calls for RaisePropertyChanged, it checks value of previously raised PropertyChanged (compares it with null) and then it raises it again (by calling it with parameter this that corresponds to SharedString and raising new PropertyChangedEventArgs, that has "e:" to indicate that it is event)?

Best regards!
Was This Post Helpful? 0
  • +
  • -

#11 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Cannot access TextBox in MainWindow.xaml.cs, which is UserControl

Posted 23 March 2013 - 05:08 PM

I use "thisUC" for the object name on UserControls and Windows alike. This makes everything consistent, so code snippets that exist for things like
{Binding ElementName=thisUC, Path=PropName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}
Always work and I only have to double-click PropName and type the new property name. It cuts down on a lot of repetitive typing.

You are correct that the two files have different organization. One was run through ReSharper to be cleaned up, reorganized and #region grouped. One was not.

You'll get to love #regions as your files get longer. When you have an individual file of a couple thousand lines it helps a LOT to have all the Button handers in one #region and all the TabPageOne methods in a #region etc. Long methods benefit from this as well. As you said, its nice when possible to have the entire method on screen. If there are large chunks of code that you know are right its nice to have them collapse to just the region title so you don't have to see that 200 lines of code.


Quote

There are also many using statements. Are they all really necessary for such a small application?

No. Many are auto imported by Visual Studio.

Quote

I understand that using #region splits code into logical parts, but it's a little bit more difficult to find something in the code if inside the region there is only short piece of code and there are many regions in short piece of code (and it cannot be shown on the screen as a whole if I don't have large screen, but only laptop).

You're making a lot of assumptions about breaking up code into lots of small parts and that really doesn't apply to #region. #region just groups things: What those things are is up to you. When you have a lot of code to go through, grouping like items makes it EASIER to find what you want quickly. When you have an issue with a property you go to that region. When you have an issue with one of your multiple constructors, they're all together. Which would you rather cut through to find one method that you know is for sending an email object:
  • Attached Image
  • Attached Image


Quote

When exactly is PropertyChanged event raised?

When this line is called:
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

To see that in action and relative to other things, put in a breakpoint and step through execution line by line with the F-10 key. Perhaps in the first line of a set method for example.
Was This Post Helpful? 1
  • +
  • -

#12 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Cannot access TextBox in MainWindow.xaml.cs, which is UserControl

Posted 23 March 2013 - 05:16 PM

Its worth noting (and using) there is a 3rd party plug-in that lets you use regions in your XAML and it is a life saver because of how long even a simple window XML can get.
http://visualstudiog...c0-c9e26bf0e177

Attached Image
Was This Post Helpful? 1
  • +
  • -

#13 johnyjj2   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 42
  • Joined: 24-July 09

Re: Cannot access TextBox in MainWindow.xaml.cs, which is UserControl

Posted 24 March 2013 - 06:09 AM

Thanks!

I have simplified my code as much as I could so the only things left are those connected with my original problem.

It compiled and launched, however DataGrid is still empty. I think its reason is that I have not binded DataGrid to the instance (object) of my class, which is created in Mainwindow.xaml.cs. So I would need to move binding from xaml to xaml.cs. But it leads me again to the original problem. I would need to access DataGrid from TestScenario.xaml inside Mainwindow.xaml.cs in order to create that binding in code, instead of xaml. I'm still working on it.

TestScenario.cs

Spoiler


TestScenario.xaml

Spoiler


TestScenario.xaml.cs

Spoiler


Mainwindow.xaml

Spoiler


Mainwindow.xaml.cs

Spoiler


Regards!

Attached File(s)


Was This Post Helpful? 0
  • +
  • -

#14 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Cannot access TextBox in MainWindow.xaml.cs, which is UserControl

Posted 24 March 2013 - 06:47 AM

Quote

I would need to access DataGrid from TestScenario.xaml inside Mainwindow.xaml.cs


Apparently my words fall on deaf ears.
You do not reach into a UserControl and directly access a GUI element on it.
You are not ready to be working on this complex application as you have not yet grasped the smaller basic concepts.

I appreciate your eagerness, but you don't seem willing to work on smaller projects of one technique at a time to get comfortable with them, before trying to put them all together. Nor do you seem willing to accept the advice being given, by shifting your goals and techniques. Unlearning these bad habits has to be a conscious choice: One you don't seem willing or ready to make yet.

I wish you the best of luck. But I don't see as my time and effort here is serving a purpose, so I'm going to bow out of the thread.
Was This Post Helpful? 1
  • +
  • -

#15 johnyjj2   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 42
  • Joined: 24-July 09

Re: Cannot access TextBox in MainWindow.xaml.cs, which is UserControl

Posted 24 March 2013 - 09:02 AM

OK, thanks,


finally I have figured it out and it works correctly now, without direct access to GUI.


My problem was that I didn't know I had to change this in Mainwindow.xaml
<local:TestScenario/>

with this
<local:TestScenario x:Name="myTestScenarioUC"/>

and I incorrectly assumed that TestScenario references to UserControl being used locally, rather than directly to GUI. (Especially that I have searched for this in some tutorials and replies on forums and they all focused on properties, without pointing to x:Name, which was the first thing I was trying to figure out, before going to add properties).


My assumption came from noticing this
<Window x:Class="WpfTest2.MainWindow"

and this
<local:TestScenario/>

So I thought that TestScenario accesses this local thing, because WpfTest2.Mainwindow.TestScenario and TestScenario were leading to the same thing.


I was also surprised earlier why I cannot access testScenarioUC which is defined like this in TestScenario.xaml
ItemsSource="{Binding ElementName=testScenarioUC,

I have added TestScenario to MainWindow in Mainwindow.xaml in this way:
<local:TestScenario/>

And TestScenario.xaml was accessing DataGrid in this way
<DataGrid Margin="5" Grid.ColumnSpan="3" x:Name="dgrNumericalParameters"
   ItemsSource="{Binding ElementName=testScenarioUC,

So I thought by using
TestScenario.dgrNumericalParameters

I would be able to access DataGrid through UserControl added locally to MainWindow, rather than directly as GUI (because of adding testScenarioUC to TestScenario and local:TestScenario to MainWindow). It looks like it does not work in this way, rather I had to use x:Name="myTestScenarioUC".


Then I could add properties in TestScenario.xaml.cs
	public partial class TestScenario : UserControl
	{
		public DataGrid ChildGrid
		{
			set { dgrNumericalParameters = value; }
			get { return dgrNumericalParameters; }
		}



And finally access it in MainWindow like this (Mainwindow.xaml.cs):
myTestScenarioUC.dgrNumericalParameters.ItemsSource = myTestClass.NumericalParameters;



Best regards!

Attached File(s)


Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2