c#WPF按钮上的更新窗口单击

时间:2018-10-30 20:30:15

标签: c# wpf

我一直在Visual Studio中弄乱c#(这是它的新手),并且一直在尝试使用WPF构建应用程序,而且我似乎无法弄清楚单击按钮时在我的环境中如何更新WPF视图。 。我已尝试将代码剔除为相关信息

我的.cs文件中有以下情况

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

我的MainWindow.xaml文件具有定义为.MainWindow的类,而MainWindow.xaml.cs文件如下所示

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();

    }

}

1 个答案:

答案 0 :(得分:0)

如果您希望在按下按钮时更新View层,则可以重新分配DataContext。例如:

public static void Eval_Click(object sender, EventArgs e)
{
    this.DataContext = new MyDataContext();
}

但是,如果您遵循MVVM模式,则您的DataContext应该继承自INotifyPropertyChanged接口,您也可以只调用PropertyChangedEventHandler事件来更新{{ 1}}层。例如:

View

...

public event PropertyChangedEventHandler PropertyChanged;  
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")  
{  
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void UpdateView()
{
    NotifyPropertyChanged("foo");
    NotifyPropertyChanged("bar");
}