首页 > 解决方案 > 获取新值时未触发我的 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 真的很陌生。

我想知道实际执行此操作的最佳形式。谢谢你们!对不起我的英语水平,我正在努力。

标签: xamarinxamarin.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会更新。


推荐阅读