【发布时间】:2021-04-18 16:28:19
【问题描述】:
当我更改作为模型对象的属性时,除非我重新分配绑定上下文,否则视图不会更新。我没有使用 mvvm,所以没有视图模型。
public partial class MainPage : ContentPage
{
private MySource _myCurrentSource = new MySource("yolor");
public MySource MyCurrentSource {
get { return _myCurrentSource; }
set {_myCurrentSource = value; }
}
public MainPage()
{
InitializeComponent();
MyCurrentSource = _myCurrentSource;
MainStack.BindingContext = MyCurrentSource;
label.SetBinding(Label.TextProperty, new Binding("SourceString"));
}
private void Button_Clicked(object sender, EventArgs e)
{
MyCurrentSource = new MySource("new string");
//property changed
MainStack.BindingContext = MyCurrentSource;
}
}
我想摆脱: MainStack.BindingContext = MyCurrentSource;
这就是我的 xaml 的样子
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="DataBindingPlayGround.MainPage">
<StackLayout Padding="10, 0" x:Name="MainStack" HorizontalOptions="Center"
VerticalOptions="CenterAndExpand">
<Label x:Name="label" Text="TEXT" FontSize="48" />
<Button Text="Change" Clicked="Button_Clicked"/>
</StackLayout>
</ContentPage>
模型类:
public class MySource
{
public MySource(string str)
{
SourceString = str;
}
public string SourceString { get; set; }
}
【问题讨论】:
-
您需要使用 INotifyPropertyChanged。请参阅docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/… 或有关此主题的数十个现有问题中的任何一个
标签: xamarin.forms data-binding