【发布时间】:2020-07-03 09:50:01
【问题描述】:
我将 MvvmCross 与 Xamarin 表单一起使用。
因此,我使用 RaisePropertyChanged 来通知 View。 但是,RaisePropertyChanged 不会在 ViewA 中触发 propertyChanged。
我不知道从哪里开始调试或检查局部变量...
流程
如果我在某处更改 Data.Value,流程如下所示。
- 已调用事件 Data.ValueChanged。
- ModelA.OnValueChanged 调用 OnPropertyChanged
- ViewModelA.OnModelPropertyChanged 调用 RaisePropertyChanged
- 预计 ViewA.OnChanged 已调用,但失败...
XAML
我运行并检查 XAML 绑定是否正常工作。
<DataTemplate x:Key="ViewB">
<ViewB Data="{Binding Data}" />
</DataTemplate>
查看
我将 BindableProperty 定义如下。
// this class is abstract!
public abstract class ViewA : MvxContentView
{
public static readonly BindableProperty DataProperty =
BindableProperty.Create(
propertyName: "Property",
returnType: typeof(Data),
declaringType: typeof(ViewA),
defaultValue: null,
propertyChanged: OnChanged);
static void OnChanged(BindableObject bindable, object oldValue, object newValue)
{
if (newValue is null) { return; }
// some codes
}
}
// actual class
public partial class ViewB : ViewA
{
public ViewB()
{
InitializeComponent();
}
}
视图模型
// this is also abstract!
public abstract class ViewModelA<T> : MvxViewModel<T>
{
protected T _model;
public Data Data
{
get => _model.Data;
}
public T Model
{
get => _Model;
set
{
if (SetProperty(ref _model, value))
{
// Register event handler
_model.PropertyChanged += OnModelPropertyChanged;
}
}
}
private void OnModelPropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "DataChanged":
{
// I expect this will fire 'propertyChanged' of BindableProperty.
// But it is not fired...
RaisePropertyChanged(() => Data);
}
break;
}
}
}
// actual class
public class ViewModelB : ViewModelA<ModelA>
{
public ViewModelB() : base()
{
}
}
型号
public class LayerModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private Data _data;
public Data Data
{
get
{
return _data;
}
set
{
if (_data != value)
{
_data = value;
_data.ValueChanged += OnValueChanged;
OnPropertyChanged("DataChanged");
}
}
}
private void OnValueChanged(object sender, EventArgs e)
{
OnPropertyChanged(""DataChanged"");
}
}
数据
public class Data
{
private int _value;
public int Value
{
get => _value;
set
{
if(_value != value)
{
// 2020.07.06 Edited
var evetArg = new DataChangedArgs
{
OldData = _value;
NewData = value;
};
_value = value;
ValueChanged?.Invoke(this, evetArg);
}
}
}
public event EventHandler ValueChanged;
}
2020.07.06 添加
public class DataChangedArgs : EventArgs
{
public int OldData { get; set; }
public int NewData { get; set; }
}
【问题讨论】: