xamarin - 获取新值时未触发我的 BindingContext 事件
问题描述
我正在设置一个简单的表单,并且我希望在表单的某些输入发生更改时得到通知,因此我将我的模型绑定到表单并为 BindingContextChanged 事件编写了一些处理程序,并且每个输入都发生了变化。
我已经尝试使输入进行双向绑定,并在每次输入更改中设置绑定上下文。
private void ContextChanged(object sender, EventArgs e)
{
if(_oldContext == null)
{
_oldContext = BindingContext as MyModel;
}
var newContext = BindingContext as MyModel;
if (newContext != _oldContext)
{
// Do something...
}
}
我对 Xamarin.Forms 真的很陌生。
我想知道实际执行此操作的最佳形式。谢谢你们!对不起我的英语水平,我正在努力。
解决方案
我想在表单的某些输入发生更改时得到通知,因此我将模型绑定到表单并为 BindingContextChanged 事件编写了一些处理程序,并且每个输入都发生了变化。
我猜你是把viewmodel绑定到当前页面的Bindingcontext,比如当前页面有一个入口控件,现在你想BindingContext会在你改变Entry'Text时更新?
如果是,我建议您可以在模型中实现 INotifyPropertyChanged,以便在 Entry'text 更改时通知。
<StackLayout>
<Entry Text="{Binding str}" />
<Button
x:Name="btn1"
Clicked="Btn1_Clicked"
Text="btn1" />
</StackLayout>
public partial class Page1 : ContentPage
{
public Page1()
{
InitializeComponent();
this.BindingContext = new MyModel();
}
private void Btn1_Clicked(object sender, EventArgs e)
{
MyModel model = BindingContext as MyModel;
Console.WriteLine("the string is {0}",model.str);
}
}
public class MyModel: INotifyPropertyChanged
{
private string _str;
public string str
{
get { return _str; }
set
{
_str = value;
RaisePropertyChanged("str");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
可以看到上面的一些代码,Entry'Text绑定了一个属性str,str在My Model类中实现了INotifyPropertyChanged,所以当你改变entry'text时,BindingContext会更新。
推荐阅读
- python - 我从命令行执行将参数传递给 URL,但由于连接无效而引发错误
- java - 无法使用 SMSmanager Android 将通话记录作为消息发送
- c++ - make_shared 是否有可能没有任何异常但返回 nullptr?
- azure - 无法使用 Azure 数据工厂在 Blob 容器内创建文件夹
- flutter - 无法使用 pub 命令安装新软件包
- mongodb - 使用 mongodb 聚合管道按升序向集合中的所有记录添加日期
- r - Combination of reshaping and aggregating a data.frame
- html - 必需的属性在 React 表单中不起作用
- sql - 如何创建可以提高图表性能的聚合表(数据集市)?
- algorithm - 给定序列具有值的概率