I have been messing around with c# in Visual Studio (rather new to it) and have been trying to build an application using WPF and I cannot seem to figure out how in my environment to update my WPF view when a button is clicked. I have tried to cull my code down to the relevant information
I have the following scenario in my .cs file
class Program
{
[STAThread]
static void Main(string[] args)
{
try
{
using (VMS.TPS.Common.Model.API.Application app = VMS.TPS.Common.Model.API.Application.CreateApplication("null", "null"))
{
Execute(app);
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
static void Execute(VMS.TPS.Common.Model.API.Application app)
{
Window window = new Window();
MainWindow mainWindow = new MainWindow(app);
mainWindow.evalButton.Click += Eval_Click //Button defined in .xaml
//Add a bunch of items
window.ShowDialog();
}
public static void Eval_Click(object sender, EventArgs e)
{
//need to add some more stuff to mainWindow and update window
}
}
My MainWindow.xaml file has class defined as .MainWindow and the MainWindow.xaml.cs file is as follows
public partial class MainWindow : UserControl
{
private VMS.TPS.Common.Model.API.Application _application;
public MainWindow(VMS.TPS.Common.Model.API.Application Application)
{
_application = Application;
InitializeComponent();
}
}
If you want your View
layer to update on button press, you can re-assign the DataContext
. For example:
public static void Eval_Click(object sender, EventArgs e)
{
this.DataContext = new MyDataContext();
}
But if you're following the MVVM pattern, your DataContext
should inherit from the INotifyPropertyChanged
interface and you can also just call a PropertyChangedEventHandler
event to update specific bindings in the View
layer. For example:
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void UpdateView()
{
NotifyPropertyChanged("foo");
NotifyPropertyChanged("bar");
}
...
public static void Eval_Click(object sender, EventArgs e)
{
(this.DataContext as MyDataContext).UpdateView();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.