xamarin.form绑定twoway对象属性不起作用

时间:2018-04-06 18:32:51

标签: xamarin mvvm binding xamarin.forms model

myview
<Image Grid.Column="0" Grid.Row="0" Source="contactIcon.png" />
<Entry Grid.Column="1" Grid.Row="0"  Text="{Binding 
SelectedContact.FNAME,Mode=TwoWay}" Placeholder="First Name" />
<Entry Grid.Column="1" Grid.Row="1"  Text="{Binding 
SelectedContact.LNAME,Mode=TwoWay}" Placeholder="Last Name"/>
<Image Grid.Column="0" Grid.Row="2" Source="calIcon.png" />
<Entry Grid.Column="1" Grid.Row="2" Text="{Binding 
SelectedContact.PHONE,Mode=TwoWay}" Placeholder="Mobile" 
Keyboard="Telephone"/>
<Image Grid.Column="0" Grid.Row="3" Source="emailIcon.png" />
<Entry Grid.Column="1" Grid.Row="3" Text="{Binding 
SelectedContact.EMAIL,Mode=TwoWay}" Placeholder="Email" Keyboard="Email"/>
<Entry Grid.Column="1" Grid.Row="4" Text="{Binding 
SelectedContact.BALANCE,Mode=TwoWay}" Placeholder="Email" 
Keyboard="Email"/>

Contact model
    public int ID { get; set; }
    public string FNAME { get; set; }
    public string LNAME { get; set; }
    public string PHONE { get; set; }
    public string EMAIL { get; set; }
    public Double BALANCE { get; set; }

ContactViewModel
private Contact _selectedContact;
public Contact SelectedContact{get { return _selectedContact; }set{ 
_selectedContact = value; OnPropertyChanged(); } }

OneWay绑定正在运行,但我想要双重绑定。如果我更改文本或修改firstname条目中的文本,那么它应该更改SelectedContact的FNAME属性

2 个答案:

答案 0 :(得分:1)

    protected void RaisePropertyChanged(String property)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }

    protected void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression)
    {
        MemberExpression expression = propertyExpression.Body as MemberExpression;
        RaisePropertyChanged(expression.Member.Name);
    }


    public event PropertyChangedEventHandler PropertyChanged;

在视图中尝试更改属性

RaisePropertyChanged(()=>YourPropertyName);

答案 1 :(得分:0)

你必须实现INotifyPropertyChanged,它是双向绑定的主要接口。你的viewmodel类必须以这种方式实现

insertInstrument

在您的MainPage()

 public class ContactViewModel: INotifyPropertyChanged 
 { 
   private Contact _selectedContact;
   public Contact SelectedContact
   { 
      get 
       { return _selectedContact; }
      set
       { _selectedContact = value;
        OnPropertyChanged(); 
       } 
    }
  public event PropertyChangedEventHandler PropertyChanged;  
  protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) {  
        PropertyChanged ? .Invoke(this, new PropertyChangedEventArgs(propertyName));  
    }
}