Xamarin 表单:如何从视图模型更改标签文本值?
Xamarin forms: How to change the label text value from viewmodel?
我想在从新页面按下后退按钮时更改上一页的标签文本值。我使用新页面的消息中心功能并将代码流重定向到视图模型中的 RefreshCustomerDetails()。
我试过如下。
string _fullname = "";
public string FullName
{
protected set
{
if (_fullname != value)
{
_fullname = value;
OnPropertyChanged("FullName");
}
}
get { return _fullname; }
}
public void RefreshCustomerDetails()
{
//FullName = null;
FullName = Application.Current.Properties["customerFullName"].ToString();
}
<Label
x:Name="title_label"
Text="{Binding FullName}"
Font="Bold,18"
TextColor="Black"
Margin="-20,0,0,0"
HorizontalOptions="CenterAndExpand"
VerticalOptions="Center"/>
从本地数据库获取全名值并像上面的代码一样绑定它,但按下后退按钮时名称没有变化。尝试分配空值,这也不起作用。
我的代码有任何更正吗?
您的代码看起来不错,应该可以工作。您的视图模型是否继承自 INotifyPropertyChanged
?这是 OnPropertyChanged()
所必需的:
public class MyViewModel : INotifyPropertyChanged
{
// stuff ...
}
更新了如下代码,删除了 RefreshCustomerDetails()
并在 MessagingCenter.
中添加 Device.BeginInvokeOnMainThread
Text="{Binding FullName,Mode=TwoWay}"
MessagingCenter.Subscribe<AddCustomerBySOPage>(this, "Refresh", (sender) =>
{
Device.BeginInvokeOnMainThread(() =>
{
FullName = Application.Current.Properties["customerFullName"].ToString();
});
});
我想在从新页面按下后退按钮时更改上一页的标签文本值。我使用新页面的消息中心功能并将代码流重定向到视图模型中的 RefreshCustomerDetails()。
我试过如下。
string _fullname = "";
public string FullName
{
protected set
{
if (_fullname != value)
{
_fullname = value;
OnPropertyChanged("FullName");
}
}
get { return _fullname; }
}
public void RefreshCustomerDetails()
{
//FullName = null;
FullName = Application.Current.Properties["customerFullName"].ToString();
}
<Label
x:Name="title_label"
Text="{Binding FullName}"
Font="Bold,18"
TextColor="Black"
Margin="-20,0,0,0"
HorizontalOptions="CenterAndExpand"
VerticalOptions="Center"/>
从本地数据库获取全名值并像上面的代码一样绑定它,但按下后退按钮时名称没有变化。尝试分配空值,这也不起作用。
我的代码有任何更正吗?
您的代码看起来不错,应该可以工作。您的视图模型是否继承自 INotifyPropertyChanged
?这是 OnPropertyChanged()
所必需的:
public class MyViewModel : INotifyPropertyChanged
{
// stuff ...
}
更新了如下代码,删除了 RefreshCustomerDetails() 并在 MessagingCenter.
中添加 Device.BeginInvokeOnMainThreadText="{Binding FullName,Mode=TwoWay}"
MessagingCenter.Subscribe<AddCustomerBySOPage>(this, "Refresh", (sender) =>
{
Device.BeginInvokeOnMainThread(() =>
{
FullName = Application.Current.Properties["customerFullName"].ToString();
});
});