如何在xaml.cs和class1.cs页面之间传递值?

时间:2014-11-24 06:42:00

标签: c# wpf windows xaml windows-phone-8

这是Main.xaml.cs页面的详细信息,

private void Btn_Ok_Click(object sender, RoutedEventArgs e)
{
    String homeTeamId = TeamIdtxt.Text;

    this.DataContext = new MainViewModel();
}

和我的class1.cs将如下所示,

public MainViewModel()
{
    Players = new ObservableCollection<PlayersViewModel>();

    string url = "http://192.168.1.19/projects/t20lite/index.php/api/api/get_playersbyteam";
    var task = new HttpGetTask<PlayerList>(url, this.OnPostExecute);
    task.OnPreExecute = this.OnPreExecute;
    task.OnError = this.OnError;

    task.Execute();
}  

我如何将hometeam id值传递给mainviewmodel,在那里我必须用url附加它。

1 个答案:

答案 0 :(得分:1)

在评论中,您可以通过以下几种方式分享数据:

选项1:使用数据绑定
http://msdn.microsoft.com/en-us/library/ms752347(v=vs.110).aspx

选项2:在ViewModel类中定义属性以传递它。添加一些方法来处理视图模型中的获取播放器请求。例如:

  public class MainViewModel
  {
     public string TeamID { get; set; }

     public MainViewModel()
     {
        Players = new ObservableCollection<PlayersViewModel>();
     }

     public void GetPlayer()
     {
        string url = "http://192.168.1.19/projects/t20lite/index.php/api/api/get_playersbyteam;"
        // Do something with url and tour TeamID
        var task = new HttpGetTask<PlayerList>(url, this.OnPostExecute);
        task.OnPreExecute = this.OnPreExecute;
        task.OnError = this.OnError;

        task.Execute();
     }   
  }  

您需要创建一次ViewModel。因此,我建议您在View的构造函数中创建ViewModel,而不是按钮单击处理程序。

  public class MainView
  {
     public MainView()
     {
        InitializeComponent();
        this.ViewModel = new MainViewModel();
     }

     public MainViewModel ViewModel
     {
        get { return this.DataContext as MainViewModel; }
        set { this.DataContext = value; }
     }

     private void TeadIdText_TextChanged(object sender, TextChangedEventArgs e)
     {
         this.ViewModel.TeamID = TeamIdtxt.Text;        
     }

     private void Btn_Ok_Click(object sender, RoutedEventArgs e)
     {         
         this.ViewModel.GetPlayer();   
     }         
  }