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");
}
There are two issues here:
- You are trying to use an instance property as though it were a static property.
- 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.
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).
精彩评论