Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have this code

C#
public partial class ScenarioEditorView : UserControl, IScreenSelectorSubItem, IActionable, INotifyPropertyChanged
   {
      
        ScenarioEditorViewModel viewModel = new ScenarioEditorViewModel(p1);


the initialization is out of the method because it is used in various methods in the class. now the problem is that it needs a parameter p1 which is a path. it has to be passed when from the other class i call it with this code:

ScenarioEditorView sev = new ScenarioEditorView(newusagepath);

now if i do this (as i am currently doing)

C#
static string p1 = "";
         ScenarioEditorViewModel viewModel = new ScenarioEditorViewModel(p1);



p1 will always be empty and it will not work. i want to pass newusagepath to p1.

i can't find it on google. pls help.
Posted
Updated 28-Jul-11 1:28am
v2

1 solution

You can:

0) Implement a public method to initialize the variable (passing the path as a parameter to the method).

1) Make a public property that can be set externally of the class that contains it

2) If the variable only has to be set one time, you could pass the path as a parameter to the class constructor, and initialize the variable inside the constructor.

3) put the variable into a static class (the least desirable implementation).
 
Share this answer
 
v2
Comments
adnama 28-Jul-11 7:48am    
you are saying to do this?


public partial class ScenarioEditorView : UserControl, IScreenSelectorSubItem, IActionable, INotifyPropertyChanged
{



public string path;


ScenarioEditorViewModel viewModel = new ScenarioEditorViewModel(path);
public void initializeviewmodel(string p)
{
path = p;
}


because path as a parameter is not found it is saying:

A field initializer cannot reference the non-static field , method, or property
#realJSOP 28-Jul-11 10:54am    
You should do ONE of the things I suggested. I really don't have time or desire to actually sit down and write and debug the code for you. For what it's worth, the way you've done it requires that you initialize "viewModel" variable in the ScenarioEditorView constructor, something like this:

public class ScenarioEditorView
{
public string path = "";
private ScenarioEditorViewModel viewModel = null;

public ScenarioEditorView(string p)
{
path = p;
initializeviewmodel(path);
}

public initializeviewmodel(string p)
{
path = p;
if (!string.IsNullOrEmpty(path))
{
viewModel = new ScenarioEditorViewModel(path);
}
}
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900