【问题标题】:Data Binding with textbox in windows phone 8windows phone 8中文本框的数据绑定
【发布时间】:2014-06-05 05:29:34
【问题描述】:

我在 XAML 中有以下代码

<Text Box x:Name="Text_Mobile_Number" 
          Height="70" Width="450" 
          Margin="24,250,0,0" 
          Text="{Binding Path=Mobile_No, Mode=Twoway, UpdateSourceTrigger=Explicit}">

我尝试将 text_box 与属性 Mobile_No 绑定,该属性在 View_Model 中定义:

private string _mobile_No;
public string Mobile_No
{
    get
    {
       return _mobile_No;
    }
    set
    {
       if(_mobile_No != value)
           _mobile_No = value;
           RaisePropertyChanged("Mobile_No");
    }
}

在 C# 中我写了一个函数,我调用了一个服务,通过它我会得到手机号码,我也在 viewmodel 中写了这个函数。

但是现在当我在按钮的单击事件上调用该函数时,调用不会转到属性,因此它没有在该属性中设置移动号码。 以下是我的函数调用:

private async void Next_AppBarIconButton_Click(object sender, EventArgs e) 
{
    LogInViewModel view_Model = new LogInViewModel();    
    var tuple = (Tuple<bool, string>)await view_Model.Get_Verification_Code();
}

但它不能正常工作,我分配的实际文本框值是 Mobile_No=Text_box.text 然后它工作正常,函数检索该值

我的实际功能:

public async Task<object> Get_Verification_Code()
{
   var flag = false;
   string message="";
   var result = (Tuple<string, string, string>)await service.Get_Verification_Code(Mobile_No,"sign_in");
}

所以请为此提出任何解决方案,我不想手动将文本框值设置为属性 Mobile_No。

我已经尝试了所有选项并搜索了所有与文本框绑定相关的sn-ps,但没有找到我在代码中出错的地方,请告诉我任何解决方案。谢谢

【问题讨论】:

  • 您是否分配了数据上下文?
  • 不。我需要分配dataContext吗??但是为什么??我不想检索值并将其显示在文本框中。那么为什么?
  • 那么 UI 怎么知道 Mobile_No 是什么
  • var view = new LogInViewModel(); this.DataContext = 视图;但它也不起作用
  • 我应该在哪里写这段代码?我在构造函数中试过了。

标签: c# windows-phone-8 data-binding


【解决方案1】:

您正在按钮单击方法中创建 ViewModel 的新实例,因此这个新实例将没有值。

在视图末尾添加以下 2 行代码(MainPage.xaml.cs)

public MainPage()
{
    InitializeComponent();
    LoginViewModel vm = new LoginViewModel();
    this.DataContext = vm;
}

将此方法更新为如下

private async void Next_AppBarIconButton_Click(object sender, EventArgs e) 
{
    LogInViewModel view_Model = this.DataContext as LoginViewModel; 
    //Now you have the instance which binded to your view which contains all the data.   
    var tuple = (Tuple<bool, string>)await view_Model.Get_Verification_Code();  
}

P.S: 我建议你使用 GalaSoft MVVM Light 框架来为你的 mvvm 应用程序

希望对你有帮助

【讨论】:

  • 非常感谢,但我不想使用 GALASOFT 库,因为我不绑定命令,我只是在点击事件上调用函数。
  • LogInViewModel view_Model = .DataContext as LoginViewModel;
  • 未在 XAML 中定义
  • 你能告诉我你的绑定 xaml 吗?那你是如何将你的虚拟机绑定到你的视图的?
  • 我猜你没有得到 MVVM 的想法。您需要将您的 ViewModel 绑定到您的视图,以从您的视图直接在您的 VM 中获取/设置值。我已经更新了原始答案,即如何将 ViewModel 绑定到您的视图
猜你喜欢
  • 2014-01-11
  • 1970-01-01
  • 2016-05-02
  • 2017-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-15
  • 2013-12-30
相关资源
最近更新 更多