Access Application.MainWindow content in usercontrol - c#

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.

Related

Secondwindow can't acces Textboxes of Mainwindow

So i have two Windows.
The first window stores all the data with textboxes, comboboxes etc.
In the second window i want to the user to enter some Information and based on the Information i want to Change something in the mainwindow.
I changed
public partial class Window2 : Window
to
public partial class Window2 : MainWindow
but it still does not work.
public partial class MainWindow : Window
{
int Languagetoken = 1;
public MainWindow()
{
InitializeComponent();
DateTextBox.Text = DateTime.Now.ToShortDateString();
}
...
public partial class Window2 : Window
{
public Window2()
{
InitializeComponent();
}
{
Do not know how to do it. The code above is not in the same xaml they just Show the initialization of both.
There are several ways to solve this but the simplest one in your case is probably to inject Window2 with a reference to the MainWindow when you create it:
Window2 win = new Window2(this);
Window2:
public partial class Window2 : Window
{
private readonly MainWindow _mainWindow;
public Window2(MainWindow mainWindow)
{
_mainWindow = mainWindow;
InitializeComponent();
}
...
}
You could then access any internal or public member of the MainWindow in Window2 using the _mainWindow reference, e.g.:
_mainWindow.textBlock1.Text = "...";
By default text boxes and all other controls are represented by private member variables int he class representing your form so you won't be able to reach into it.
In order access it from outside, you can add a property inside the first window...
public string DataText
{
get
{
return DataTextBox.Text;
}
set
{
DataTextBox.Text = value;
}
}
Or you can change the access level of the controls to internal or public so that you can access it by using a reference to the window.

Stack Overflow when trying to access form controls from class

I have a problem, after adding this code so I can access my MainWindow controls in Downloader class:
public partial class MainWindow : Form
{
private Downloader fileDownloader;
public MainWindow()
{
InitializeComponent();
fileDownloader = new Downloader(this);
}
//smth
}
and
class Downloader : MainWindow
{
private MainWindow _controlsRef;
public Downloader(MainWindow _controlsRef)
{
this._controlsRef = _controlsRef;
}
// smth
}
it now gives me "An unhandled exception of type 'System.StackOverflowException' occurred in System.Windows.Forms.dll" on line
this.mainControlPanel.ResumeLayout(false);
in MainWindow.Designer.cs. If i comment out the code above, it works fine. Any ideas please?
PS. Also, when I'm in Downloader class, should i access the controls like
textbox.Text
or
_controlsRef.textbox.Text
Both seem to give no compile errors, is there any difference between the two?
Your Downloader class inherits MainWindow. When you instansiate it, according to the C# specification, the base class is initialized first. When MainWindow initializes, it creates a new instance of Downloader, which causes it eventually to stackoverflow, because you're in an endless cyclic dependency.
Since Downloader inherits MainWindow, there is no point in getting an instance of it via your constructor. You can simply access it's protected and public members from your derived.
For example:
public partial class MainWindow : Form
{
protected string Bar { get; set; }
public MainWindow()
{
Bar = "bar";
InitializeComponent();
}
}
public class Downloader : MainWindow
{
public void Foo()
{
// Access bar:
Console.WriteLine(Bar);
}
}
It's problem because here you are having cyclic dependancy i.e. both the method waiting for each other to complete.
check
public MainWindow()
{
InitializeComponent();
fileDownloader = new Downloader(this);//this wait to complete downloader intialization
}
public Downloader(MainWindow _controlsRef)//this wait to complete mainwindow first
{
this._controlsRef = _controlsRef;
}
my mean to say as you are inheriting Downloader from MainWindow , which in constructor crating downloader instace...and downloader calls Mainwindow constructor first as its parent crates problem for you here
Solution
if want reference you can do like this
public partial class MainWindow : Form
{
protected MainWindow mainWindow;
public MainWindow()
{
InitializeComponent();
mainWindow = this;
}
//smth
}
class Downloader : MainWindow
{
public Downloader()
{
//this.mainWindow //will give you reference to main winsow
}
// smth
}

Accessing UserControl Methods and properties from other Class

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
}
}

When accessing window from view model it is always null

What i want to do is to create property into the model ComboBoxItemChange.cs of type ILoginView that is the interface which LoginWindow.xaml.cs is deriving. Using this property i want to grant access to the elements inside LoginWindow. I red that this is correct way to do it using MVVM pattern.
My problem is that property is always null.
LoginWindow.xaml.cs
public partial class LoginWindow : Window, ILoginView
{
public LoginWindow()
{
InitializeComponent();
this.DataContext = new ComboBoxItemChange();
(this.DataContext as ComboBoxItemChange).LoginWindow = this as ILoginView;
}
public void ChangeInputFieldsByRole(string role)
{
MessageBox.Show(role);
}
}
ComboBoxItemChange.cs
public class ComboBoxItemChange : INotifyPropertyChanged
{
public ILoginView LoginWindow { get; set; }
private void ChangeloginWindowInputFields(string value)
{
if (LoginWindow == null)
return;
LoginWindow.ChangeInputFieldsByRole(value);
}
}
ILoginView.cs
public interface ILoginView
{
void ChangeInputFieldsByRole(string role);
}
As stated in comment:
There are two different instances you are creating:
One in code behind where you set ILoginView to window itself
Second in Grid resources where you haven't set ILoginView.
Remove the instance you declared in XAML and let the bindings resolved from the instance you created in code behind. (DataContext will automatically be inherited for child controls).

Using and instance of a class on two forms

I am struggling to get my head around the following.
I current have three forms, my main and one main class.
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
}
public partial class frmSuppliers : Form
{
public frmSuppliers()
{
InitializeComponent();
}
}
public partial class frmCustomers : Form
{
public frmCustomers()
{
InitializeComponent();
}
}
In my main program I have:
public class Program
{
public StockControl StockSystem = new StockControl("The Book Shop", 20);
}
I want to be able to access the methods from StockControl in frmSuppliers and frmMain.
I know this may be a N00b question - but its been bugging me all day!
You need to pass it to the other forms as a constructor parameter, then store it in a private field.
declare it static
public static StockControl StockSystem = new StockControl("The Book Shop", 20);
and use as
Program.StockSystem
You should add a field of type StockControl to each of your forms, and make it public, or add getter/setter to it. This means adding the following lines to each one of your forms:
private StockControl _stockCtrl;
public StockControl StockCtrl
{
get { return _stockCtrl; }
set { _stockCtrl = value; }
}
The in the cod of each form you can access your StockControl. But it will be empty (i.e. null) if you don't assign it something. This is something I'd do before opening the form. If you are in your main method:
frmSuppliers frmToOpen = new frmSuppliers();
frmSuppliers.StockCtrl = StockSystem;
frmSuppliers.Show();

Categories