如何在 xaml.cs 到 class1.cs 页之间传递值
本文关键字:cs 之间 xaml class1 | 更新日期: 2023-09-27 18:31:45
这是 Main.xaml.cs 页面详细信息,
private void Btn_Ok_Click(object sender, RoutedEventArgs e)
{
String homeTeamId = TeamIdtxt.Text;
this.DataContext = new MainViewModel();
}
而我的班级1.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();
}
我必须如何将主队 ID 值传递给主视图模型,在那里我必须用 url 附加它。
如注释中所述,您可以通过以下几个选项共享数据:
选项 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();
}
}
而且您需要创建一次视图模型。因此,我建议您在视图的构造函数中创建视图模型,而不是单击按钮处理程序。
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();
}
}