views:

26

answers:

2

I was recently having some issues with a bigger project, but in an effort to solve the problem, I made a new solution with just two incredibly basic files. It is a WPF C# project with the main window containing a button, and a usercontrol containing a textblock. I already have them linked in Blend so that when I click the button, the usercontrol comes up. However, when I added code to change the text in the usercontrol's textblock from the mainwindow, it gives me this error: An object reference is required for the non-static field, method, or property TestingUserControls.TestControl.sampleText.get'

I like usercontrols and we are using them all throughout our project, but for some reason I just cannot get them to work well.

The code for my usercontrol is this:

public TestControl()
        {
            this.InitializeComponent();
        }

        public string sampleText
        {
            get { return blkTest.Text; }
            set { blkTest.Text = value; }
        }

The code for the main window is this:

public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            TestControl.sampleText.set("Sup");
        }
A: 

There are two issues here:

  1. You are trying to use an instance property as though it were a static property.
  2. The syntax you are employing to invoke a property-setter is not correct.

Make sure you have a reference to an instance of TestControl. For example, you can use the WPF designer to drag an icon representing the control from the toolbox onto the main-window, and then change the body of the handler to:

testControl1.sampleText = "Sup";

In this case, testControl1 is a field, which references an instance of your control.

Ani
Well to be honest, I changed my code to that after digging around google for a while trying to find the answer. I'm sure it's no better, but originally I had nothing in the usercontrol and in the mainwindow I had "blkTest.Text = "testing!!!!"
zack
@zack: The problem still persists?
Ani
No, you just fixed an entire week of headache for me. My group and I have been trying to figure out why we could never set data on a usercontrol and now we know. I can't believe it was so simple! Thanks for your quick help.
zack
@zack: Cheers, good to hear.
Ani
A: 

Your question already has the answer you are looking for....

"An object reference is required for the non-static field, method, or property TestingUserControls.TestControl.sampleText.get'"

You are trying to access non-static property of an object using the type name (not the instance).

Rather try setting the property by using the instance of TestControl (x:Name in the xaml).

Amby