Accessing UserControl Methods and properties from other Class - c#

What i have is a user control which contains a combobox and a DataGrid , what am trying to do is Accessing the UserContorl Methods from within my other Class which is named Class1 , in the class 1 i have some methods which will take advantage of the method in the UserControl(since the user control contains necessary data like combobox.tex)
//The user control Code
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public string Mymethod()
{
return Combobox.Text ;
}
}
// The other class is
class Class1
{
//Here i want to access the method from the withen of the userControl Class
UserControl1 cnt= new UserControl1()
//Also tried var cnt= new UserControl1()
Cnt.MyMethod()
}
What i have been trying is to create an instance of UserContorl in Class1 but i get no result since it is a new instance . Even at some point i have created a property inside the UserControl Class to pass up neccesary data but no luck as well .

You expose the form to Class1 by passing it as a parameter to the constructor:
class Class1
{
private readonly UserControl _userControl;
public Class1(UserControl userControl)
{
_userControl = userControl;
}
public void SomeMethod()
{
_userControl.MyMethod() etc
}
}

Related

C#: Referencing an instance of a class that was made in another class

I need some help with C#.
Let's say I have 3 classes. MainMenu, Form1 and Data.
I have created an instance of Data (referenced as StoreData) in MainMenu.
public partial class MainMenu : Form
{
public Data StoreData = new Data();
}
I want to be able to access this instance of StoreData in Form1. How do I reference it or import it?
You can either
Make StoreData static 🤮 in a static class MyAWesomeStatic and call MyAWesomeStatic.StoreData or even in MainMenu class iteself.
Pass a reference of StoreData to Form1 either via the constructor or a property when you create it.
or pass a reference of MainMenu to form1 and call mainMenu.StoreData when needed.
However, another option might be to use Dependency Injection (DI) and Loosely Couple all this. Have a Singleton instance and pass the in-memory Data Store as some sort of Service (which is what the cool kids might do).
Update
Sorry, still at the beginning stages of learning C#. What does it mean
to make a class static?
Given your current level of knowledge and all-things-being-equal, i think the easiest approach might be just pass in a reference
public class Form1
{
public Data StoreData { get; set; }
}
...
var form = new Form1();
form.StoreData = StoreData;
form.Show();
If you want to reference one class within another class (and don't want to make anything static), composition is one way to go.
You want to reference field of MainForm in Form1, so you want to reference MainForm itself. Thus, you need to create field in Form1 of MainForm type:
public class Form1 : Form
{
...
public MainForm mf { get; set; }
...
}
Now, you can access StordeData with mf.StordeData within Form1.
You could make StoreData static in a static class, something like this:
public static class Form1
{
public static Data StoreData { get; set; }
}
Suppose your StoreData class have one property
public class StoreData
{
public int MyProperty { get; set; }
}
Add static property to your mainform.cs and assign value to MyProperty = 1
public partial class MainMenu : Form
{
public static StoreData Data { get; set; } //static property
private void MainMenu_Load(object sender, EventArgs e)
{
Data = new StoreData { MyProperty = 1 };
}
}
And access your StoreData property inside Form1.cs like
public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e)
{
var id = MainMenu.Data.MyProperty;
}
}
Try once may it help you
Result:

How to inherit ViewModel class to UserControl?

Suppose that I've a ViewModel class with different property such as:
//MainVm will inherit ViewModel that contains IPropertyChanged implementation
public class MainVM : ViewModel
{
publi bool Foo { get; set; }
}
I instatiated this class on the main controller in this way:
MainController mc;
public MaiWindow()
{
mc = new MainController();
DataContext = mc;
InitializeComponent();
}
the MainController have this implementation:
public class MainController : MainVM
{
some methods
}
so each time I need to access to a property of MainController on each UserControls I need to do: Application.Current.MainWindow.mc.Foo
and this is't elegant at all.
Is possible access to the property of specific ViewModel without call the code line above?
Thanks.
UPDATE
For add more details and clarification to this question: so in my UserControl I need to access to the Foo property that is part of MainVM. I'm spoke about the UserControl xaml code (not the controller of the UserControl), this is an example:
public partial class ControlName : UserControl
{
public ControlName()
{
InitializeComponent();
}
public btnAdd_Click(object sender, RoutedEventArgs e)
{
//Suppose that I need to access to the property Foo of MainVM here
//I need to access to MainWindow instance like this:
Application.Current.MainWindow.mc.Foo
//isn't possible instead access to the property directly inherit the class, like:
MainVm.Foo
}
}
In order to get the configuration App-Wide, you could use the
ConfigurationManager.AppSettings["Whatever"];
These settings are located in the App.Config in the following form
<appSettings>
<add key="Whatever" value="Hello" />
</apSettings>
But as I undertand, you have a ViewModel that let Users change the settings, in this case you should go for:
Properties.Settings.Default.myColor = Color.AliceBlue;
You ViewModel could expose this property as:
public Color MyColor
{
get {
return Properties.Settings.Default.myColor;
}
set {
Properties.Settings.Default.myColor = value; RaisePropertyChanged();
}
}
public void Persist()
{
Properties.Settings.Default.Save();
// Raise whatever needed !
}
From other ViewModels you can access these setting as well:
Properties.Settings.Default.myColor
Have a look here https://learn.microsoft.com/en-us/dotnet/framework/winforms/advanced/using-application-settings-and-user-settings and here https://learn.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-create-application-settings

Visual C# Access item from other class file

im writing an application in visual studio and im trying to access a rich text box from an other class. This doesnt seem to work for me. Also how to i call a function from an other class?
My code:
namespace Test{
public partial class Form1 : Form
{
public Form1()
{
// I want from this place to access the MyClass.test("hello");
}
}
}
namespace Test{
class MyClass
{
public void test (string text)
{
// here i want to do richtextbox1.clear(); but the textbox is not available
}
}
}
can be done in many ways. My favorite would be to declare the object of the "MyClass" class within "Form1" by passing the "this" pointer as an argument. Thus, the object of the "MyClass" class will have access to all the members and public functions "Form1". Included RichTextBox1.
namespace Test{
public partial class Form1 : Form
{
MyClass MyClassObject;
public Form1()
{
InitializeComponent();
MyClassObject=new MyClass(this);
MyClassObject.test("hello");
}
}
}
namespace Test{
class MyClass
{
Form1 parent;
public MyClass(Form1 parentForm)
{
parent=parentForm;
}
public void test (string text)
{
parent.richtextbox1.clear();
}
}
}
You don't want to do this. You can for example do it like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var myClass = new MyClass(this.richtextbox1);
myClass.SetTextBoxText("hello");
}
}
class MyClass
{
RichTextBox _textBox;
public MyClass(RichTextBox textBox)
{
_textBox = textBox;
}
public void SetTextBoxText(string text)
{
_textBox.Clear();
_textBox.Text = text;
}
}
This uses constructor injection to pass the textbox to operate on to the contstructor. In Form1's constructor the MyClass is instantiated with a reference to the textbox, which is initialized in InitializeComponent(). Then when you call SetTextBoxText, the class clears the associated textbox's text and then sets it to the passed text.
This is more specific than the commonly suggested method: just pass the entire Form1 instance to MyClass's constructor after making the textbox public, but that way you cannot reuse MyClass for other forms.
But as you see, it's pretty pointless to do. You can let Form1 contain this.richttextbox1.Text = "hello"; directly.
It is not quite clear from your question, but I'm supposing your richtextbox1 is located at Form1.
By default all UI elements of form has private acess modifier - that's why you can't access your richtextbox1 from outer class.
You can change it's access mmodifier to public - but I strongly encourage you not to do it.
Instead write some method in Form1 class like
public void ClearRichTextBox()
{
richtextbox1.Clear();
}
and use it.

Access Application.MainWindow content in usercontrol

In WPF application it is easy to access MainWindow content but how to do in usercontrol.
In WPF Application, if my MainWindow name is Window1 and i have to access its one of the string variable named CName from some other class in same application.
Window1 ww = Application.Current.MainWindow as Window1;
String reqstring = ww.CName ;
I want to do same thing in usecontrol too.
Assume my usercontrol name is ABCcontrol and first/main Class name is ABCconrolLib
namespace ABCcontrol
{
public partial class ABCcontrolLib : UserControl
{
Public String CName = "ABC";
//....
}
}
Now i want to access this CName in some other class of same usercontrol by using Application.Control.MainWindow or by some other similar way
Please help me out as this is my first UserControl in WPF
You can access Application.Current.MainWindow because you have just one instance of MainWindow in your whole application so they defined it as a static property.
If you have the same characteristic for your users control (just you need to use a single instance of it in the whole application) you can define a static property there as well.
Something like :
then you can access name property like UserControl1.Instance.CName
public partial class UserControl1 : UserControl
{
public static UserControl1 Instance
{
get;
private set;
}
Public String CName = "ABC";
public UserControl1()
{
if (Instance != null)// there should be just one instance
throw new NotSupportedException();
Instance = this;
InitializeComponent();
}
}
if you get error then you do not have just one instance of your usercontrol, you have to define a List and register each instance of your users controls there. Something like:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
(App.Current as App).UserControl1List.Add(this);
InitializeComponent();
}
}
public partial class App : Application
{
public App()
{
UserControl1List = new List<UserControl1>();
}
public List<UserControl1> UserControl1List
{
get;
private set;
}
}
then you can reach to each instance like (App.Current as App).UserControl1List[0]...
or you can use a dictionary for storing each UserControl there.

c# how do i access my form controls from my class?

I have a class in the same namespace as my form. Is it possible for me to access methods/properties of my form controls from my class? How can I accomplish this?
You need to make your controls public, however I wouldn't do that. I'd rather expose just what I need from my controls. So say if I needed access to the text in a text box:
public class Form1 : Form
{
public string TextBoxText
{
get{return this.textBox1.Text;}
set{this.textBox1.Text = value;}
}
}
One way is to pass the form into the class like so:
class MyClass
{
public void ProcessForm(Form myForm)
{
myForm.....; // You can access it here
}
}
and expose the Controls that you want so that you can access them but really you should pass only what you need to the class, instead of the whole form itself
If you pass a reference of your form to your class you should be able to access methods and properties of your form from your class:
public class MyClass
{
private Form form;
public void GiveForm(Form form)
{
this.form = form;
}
}
You need to generate stubs.
For that
In your custom class write a constructor
public YourClass(Main main)
{
// TODO: Complete member initialization
this.main = main;
}
then in main class/form class, initialize your class
YourClass yesMyClass = YourClass(this);
If your want to access form components on your custom class then,
this.main.label1.Text="I done that smartly'

Categories