【问题标题】:How to call method having parameters (object sender, EventArgs e )如何调用具有参数的方法(对象发送者,EventArgs e)
【发布时间】:2013-07-06 16:48:16
【问题描述】:

在我的 wpf 应用程序中,我有一个定义此方法的 MonthView 类,它从日历中获取选定的日期并显示该日期的相应 dayView 窗口。

public void calItemSelectedDate(object sender, SelectionChangedEventArgs e)
    {
        DateTime d;
        if (sender is DateTime)
        {
            d = (DateTime)sender;
        }
        else
        {
            DateTime.TryParse(sender.ToString(), out d);
        }
        DayView Activity = new DayView(d);
        Activity.Show();
        this.Hide();
     }

现在,在我的 CustomView 类中,我创建了 dayView 的实例,我想在其中传递选定的日期。

DateTime p = Globals._globalController.getMonthViewWindow.calItemSelectedDate(object s, EventArgs e); // here it shows error
DayView d = new DayView(DateTime p);

所以,请建议调用“calItemSelectedDate”方法的方法,以便我可以将适当的日期时间参数传递给我的 DayView。

【问题讨论】:

  • 尝试 DateTime p = Globals._globalController.getMonthViewWindow.calItemSelectedDate(this, null);
  • @DatRid 在“this”关键字处仍然显示错误。

标签: c# wpf datetime parameter-passing function-calls


【解决方案1】:

引用的方法是一个事件处理程序,而不是直接调用的最佳选择。 在这种情况下,我会做的是:

//A PROPERTY THAT SAVES SELECTED DATE VALUE
public DateTime SelectedDate {get;set;}

//A METHOD THAT SHOWS ACTIVITY 
public void ShowActivity(DateTime date) {
    DayView Activity = new DayView(date);
    Activity.Show();
    this.Hide();
}

public void calItemSelectedDate(object sender, SelectionChangedEventArgs e)
{
    DateTime d;
    if (sender is DateTime)
    {
        d = (DateTime)sender;
    }
    else
    {
        DateTime.TryParse(sender.ToString(), out d);
    }

    SelectedDate = d;

    ShowActivity(d);
 }

从你想调用它的班级:

DateTime p = Globals._globalController.getMonthViewWindow.SelectedDate;
DayView d = new DayView(p);

【讨论】:

  • 我试过你的代码,但是,它在传递给 DayView 时显示错误。
  • 错误是“字段初始化器不能引用非静态字段方法或属性”
  • 检查您的可访问性 public/static... 在这些调用中:Globals._globalController.getMonthViewWindow
  • 非常感谢。实际上,我在类内部但在构造函数外部编写了这两行。但是进入构造函数后,它工作正常。
猜你喜欢
  • 2013-02-19
  • 1970-01-01
  • 2010-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多