Unable to set a TextBox text owned by MainWindow from another class - c#

I am trying to set a TextBox value text owned by MainWindow (WPF Window) from another class in the same namespace, but nothing happens. I've gone through many suggestions and answers to similar questions with no avail. What puzzles me is that MainWindow's SetText receives the text as it is being displayed in Visual Studio console, but doesn't have any effect on the actual textbox. The 'ConsoleLog' textbox has the default XAML values.
So my MainWindow is similar to this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public string SetText
{
get { return ConsoleLog.Text; }
set {
Console.WriteLine(value);
ConsoleLog.Text = value;
}
}
}
In my App class:
public partial class App : Application
{
private void Test()
{
var mw = new MainWindow();
mw.SetText = "Please display something!";
}
}
I tried with several other methods such as:
((MainWindow)System.Windows.Application.Current.MainWindow).ConsoleLog.Text = "Please display something!";
but nothing works so far without any error messages.
I'm fairly new to WPF C# and I'm sure it is something very obvious I'm missing, but it drives me crazy.

WPF project Default project start up MainWindow by configuring its App.xaml file, not by app.xml.cs. if you want to get access to MainWindow , you should initiate MainWindow manually by following code
public App()
{
var mw = new MainWindow();
mw.SetText = "Please display something!";
mw.ShowDialog();
}
and remove the following line from App.xaml
StartupUri="MainWindow.xaml"
if you want to get started with WPF application and make a good app,I recommend you to see some basic tutorial, and try to learn MVVM (or MVC in web) programming methodology.

Related

How to access a MainWindow variable from a page in C# WPF?

I am trying to code a WPF desktop Application. Currently i have a Main Window (MainWindow) and a page (Pageone) under the same solution. From my MainWindow.xaml.cs page, i have a variable (proc1) which i want to pass to my Pageone.xaml.cs page and maybe even more pages in the future to access and use for some calculation.
However i cant seem to find a method to successfully do this, i have tried making my variable "public", and instantiate the MainWindow object for my page to access it but it doesn't seem to work. (A field initializer cannot reference the non-static field, method, or property 'Pageone.pog')
MainWindow.xaml.cs
public string proc1;
public void startTroubleshootButton_Click(object sender, RoutedEventArgs e)
{
try
{
var selectedProcess = listViewProcesses.SelectedItems[0] as myProcess;
if (selectedProcess == null)
{
MessageBox.Show("no selection made");
return;
}
proc1 = selectedProcess.processName;
MessageBox.Show($"you have selected the {proc1} application ");
Pageone pg = new Pageone(this);
this.Content = pg;
}
catch(ArgumentOutOfRangeException)
{
return;
}
}
Pageone.xaml.cs
public partial class Pageone : Page
{
public Pageone(MainWindow mainWindow)
{
InitializeComponent();
}
MainWindow pog = new MainWindow();
string procName = pog.proc1;
...
I've heard that i will maybe need to use something called the MVVM or code a parameterized constructor but i'm not sure if its related to the code i'm doing. Is there a better way to go about coding this? Thanks.
It can be done like:
var window = (MainWindow)Application.Current.MainWindow;

How to load ViewModel/View in WPF under CaliburnMicro

I have a timer in my wpf application wich every 5 minutes ask a WCF service. If the service have message for my application, I get a list which contains text data and a specific code.
This code give an information about the view which must be loaded to print the data.
I have two ViewModel (the data source is the same for both): One for a Ticker > one view and One for Popup > two view
Project files :
View
Popup
PopHighView.xaml
PopMediumView.xaml
Ticker
TickerLayout.xaml
TickerNormal.xaml
ViewModel
PopViewModel
TickerViewModel
Models
AlertModel.cs
ViewParsers
AlertParser.cs
Datasource :
public class AlertParser : IAlertParser{
AlertServiceClient service;
public List<AlertModel> TickerAlertData()
{
try
{
service = new AlertServiceClient();
List<AlertModel> items = (from item in service.GetActiveAlert() select new AlertModel
{
Alertid= item.AlertId,
Alertstartdate = item.AlertStartDate,
Alerttitle = item.AlertTitle,
Alerttxt = item.AlertText
}).ToList();
return items;
}
catch
{
return null;
}
}
}
When my application is launched, there is no loaded view, only a icon in the systray(with wpf notifyicon).
My problem is, under theses circonstances, I don't understand how I could loaded a couple ViewModel/View, and pass the data to them, when my timer return a true from my service.
Many examples on the web have a mainview loaded, that's why I'm lost (like Conductor example on caliburn micro page).
Thanks for any help !
Edit :
Ok, My timer look like that :
if (service.IsAlertReady()=true)
{
string hostName = Dns.GetHostName();
string myIP = Dns.GetHostEntry(hostName).AddressList[0].ToString();
service.IsAlertForMe(myIP);
if(service.IsAlertForMe(myIP) == true)
{
ShellViewModel shell = new ShellViewModel();
shell.ShowMediumPop();
}
else
...
ShellViewModel
public class ShellViewModel : Conductor<object>
{
public void ShowMediumPop()
{
ActivateItem(new PopViewModel());
}
}
PopViewModel
public class PopViewModel : screen
{
protected override void OnActivate()
{
base.OnActivate();
}
}
PopView.Medium
<UserControl x:Class="TerminalClientProto.View.PopView"
...
cal:View.Model="{binding}"
cal:View.Context="Medium"
>
I'm sorry but I don't understand how I could launch my view when my Ticker tick. I've read the documentation, but I need some hints to understand this mechanism.
A program, any program, including the very program that contains the views you want to display can show a view in a number of ways. Here's a few:
var app = new App();
app.InitializeComponent();
app.Run();
Or you can start the view directly:
var view = new MyView();
view.Show();
// or
view.ShowDialog();
If the view is a MainWindow, then you can create a ContentControl area within the view to inject the Usercontrol containing the sub-view of what you want displayed. This still requires the MainWindow to be open... So the examples above would also work when injecting UserControls into a MainWindow. The act of injecting a User control is setting the ContentControl's Content to an instance of the User Control itself. Eventhandlers can handle this scenario nicely...
public void NewUserControlInMainWindow(object sender, UserControl uc){
//XCC = the Xaml content control in main window
XCC.Content = uc;
}
I'm not really sure how Caliburn does view injection....

how to pass data from one window to another?

I am working on C# wpf, and I am trying to create 'favorite' function on it.
There is one window called 'favorite' and it is where a user can save his data.
Another window is 'MainWindow' and I want to load the data here.
There are two buttons and two textbox in 'favorite'.
If I type words in each box, I hope they can be saved if I click star1button.
And if I type another words in each box, I hope they would be saved if I click star2button.
So I hope each data will be stored separately, without being overlapped.
And then, if I press button1 on 'mainwindow', I hope those words of star1button would show up in textboxes of mainwindow.
And if I press button2 on mainwindow, I hope words of star2button would show up in textboxes of mainwindow.
Thanks in advance!!
You can place an attribute in your App.xaml.cs which should be accessible from both
namespace MyApp
{
sealed partial class App : Application
{
public string myValue;
// the rest of your App.xaml.cs code
}
}
Then in your MainWindow and other window put this code
public string MyValue
{
get
{
return (Application.Current as MyApp.App).myValue;
}
set
{
(Application.Current as MyApp.App).myValue= value;
}
}
You can use a static class to pass values between windows.
public static class CurrentParameters
{
public static string mySharedValue { get; set; }
}

Property reverts to original value once second window closes

I have a ViewModel which is bound to my MainWindow. I have a property in my ViewModel I want to bind to a second window which opens after selecting a menu item. Here is the property I have bound to the second window. So far so good
private string _displayPathToLib;
public string DisplayPathToLib
{
get { return _displayPathToLib; }
set
{
_displayPathToLib = value;
OnPropertyChanged("DisplayPathToLib");
}
}
I use a command using the ICommand interface to open the second window. Here is a snippet
public void Execute(object parameter)
{
BrowseDialog winBrowseDialog = new BrowseDialog();
Nullable<bool> BrowseDialogResult = winBrowseDialog.ShowDialog();
The second window opens as it should and allows me to edit the text box that is displayed. I am able to to see the "DisplayPathToLib" property change when I type something in the textbox (by setting the debug break). But upon closing the window the value of "DisplayPathToLib" reverts to NULL. Below is a snippet of the code behind I am using to handle the ok button click
private void okButton_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
Close();
}
Why does the property keep reverting back to NULL? How do I get the "DisplayPathToLib" to retain its value??? I have tried everything. I also tried maintaining a MVVM pattern but could not get the OK button to work without code-behind. :-(
I solved my problem by setting the datacontext of my new window directly to my ViewModel. To ensure your ViewModel's data keeps the bound values from multiple windows set the new instance of your second window (or multiples windows) to your ViewModel like so...
class UserSettingsCommand : ICommand
{
MainVM _data; //MainVm is my ViewModel class
public UserSettingsCommand(MainVM data)
{
_data = data;
}
.
.
.
public void Execute(object parameter)
{
BrowseDialog winBrowseDialog = new BrowseDialog(); //Instantiate a new custom dialog box
winBrowseDialog.DataContext = _data; //THIS IS WHERE I SET MY VIEWMODEL TO THE NEW WINDOWS DATACONTEXT
Nullable<bool> BrowseDialogResult = winBrowseDialog.ShowDialog();
.
.
.
I am new to C# and I am just learning the MVVM pattern so while this is probably common knowledge, maybe someone new can save some time. Using the MVVM pattern with one window did not require this step. DataContext is set for my MainWindow in the MainWindow.xaml.cs file so I assumed this could be done for the second windows secondwin.xaml.cs file. The only way I got it to work was by setting the DataContext as shown in the code above ....not in the .cs file.

How do i show a new form from usercontrol?

I'm making a usercontrol which is a file manager (cut ,copy ,paste .. etc)
so while moving/coping files .. i had to show a messagebox when the file is already exist .. to let the user to confirm overwrite it or cancel .. but i need 4 buttons [YES][YES TO ALL][NO][CANCEL]
so i made a new form called "MyMessageBox" which contains the 4 buttons and a label.
my problem is .. in (userControl1.cs) i can't initialize the form like this:
MyMessageBox msgbox = new MyMessageBox("overwrite file ?");
First of all you need to make sure that your usercontrol has visibility of the form that you created(i.e. if your form is in another namespace or project you will need to use a using statement or add a project reference in order for your usercontrol to be able to use it.) and that your constructor is what you are thinking it is as M.Babcock is suggesting. You can try something like this
UserControl:
public partial class UserControl1 : UserControl
{
MyMessageBox msgbox;
public UserControl1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
msgbox = new MyMessageBox("Overwrite File ?");
msgbox.ShowDialog();
}
}
CustomMessageBox:
public partial class MyMessageBox : Form
{
public MyMessageBox( string Message)
{
InitializeComponent();
label1.Text = Message;
}
}
Which will give you a result like this.

Categories

Resources