我有一些XAML
public interface RequestInterface {
@GET("v1/articles?source=mashable&sortBy=top&apiKey=your_apikey_here")
Call<JSONResponse> getJSON();
}
XAML后面的cs页面/代码页获取绑定上下文集:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://newsapi.org/")
.addConverterFactory(GsonConverterFactory.create())
.build();
一个名为UIBindingProperties.cs的单独类,我定义了我的属性。在这里,我尝试实现INotifyPropertyChanged,但我认为这样做不正确:
<Label x:Name="AYCOBRO" Text="{Binding COBRO}" Margin="10,10,0,0"/>
现在从后台工作者类我尝试更新要在UI中反映的属性:
BindingContext = new UIBindingProperties();
什么都没发生。这有什么不对?
更新
开始使用Refractored.MvvmHelpers nuget,我的UIBindingProperties类现在看起来像这样:
public class UIBindingProperties : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public string COBRO
{
get
{
return COBRO;
}
set
{
COBRO = value;
OnPropertyChanged(nameof(COBRO));
}
}
}
仍然没有成功......
更新2除了下面接受的答案,我添加到app.xaml.cs
Device.BeginInvokeOnMainThread(() =>
{
var t = new UIBindingProperties();
t.COBRO = amounttopay;
//I can see the property being set with this //
Debug.WriteLine("your COBRO propertie is: " + t.COBRO);
});
有了这个,我可以访问这个应用程序范围的viewmodel。
答案 0 :(得分:2)
不要试图重新发明轮子。查看James Montemagno撰写的MvvmHelpers,并使用BaseViewModel
作为UIBindingProperties
更清楚。将MvvmHelpers NuGet添加到您的项目中并使用实现BaseViewModel
的{{1}},如下所示
INotifyPropertyChanged
编辑:
我刚注意到您正在创建新对象public class UIBindingProperties : BaseViewModel
{
private string name;
public string Name
{
get => name;
set => SetProperty(ref name, value);
}
}
。这意味着您现在使用完全不同的对象,然后使用您设置为var t = new UIBindingProperties()
的对象(即对象设置为ViewModel
)。为您的BindingContext
(即ViewModel
)创建一个字段,将其分配到您网页的UIBindingProperties
,然后在相同的对象上更新该属性。代码看起来像这样:
BindingContext