我正在使用可绑定(bind)的StackLayout
显示一系列Entry
绑定(bind)到ObservableCollection<string>
( Addresses
在 viewModel 下)。
在 UI 上显示集合的内容不是问题,但是如果我修改 Entry
中任何一个的内容,它不会反射(reflect)在原始 ObservableCollection
中
这是 View 模型:
public class MainViewModel
{
public ObservableCollection<string> Addresses { get; set; }
public ICommand AddCommand { get; private set; }
public MainViewModel()
{
AddCommand = new Command(AddEmail);
Addresses = new ObservableCollection<string>();
Addresses.Add("test1");
Addresses.Add("test2");
}
void Add()
{
AddCommand(string.Empty);
}
}
这是 View :
<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="TestList.MainPage"
x:Name="page">
<StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="Addresses"
FontSize="Large"
HorizontalOptions="FillAndExpand"
VerticalOptions="Center"/>
<Button Command="{Binding AddCommand}"
Text="+" FontSize="Title"
VerticalOptions="Center"/>
</StackLayout>
<StackLayout BindableLayout.ItemsSource="{Binding Addresses}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<StackLayout Orientation="Horizontal">
<Entry Text="{Binding ., Mode=TwoWay}" HorizontalOptions="FillAndExpand"/>
<Button Text="-" FontSize="Title""/>
</StackLayout>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</StackLayout>
</ContentPage>
我怀疑这是因为我正在处理字符串,因此无法就地修改它们。您对如何在不引入包装类或类似类的情况下解决此问题有什么建议吗?
最佳答案
如果你想通过编辑 Entry 中的文本来更改代码后面的 source 的值,则需要在 ObservableCollection 类中实现接口(interface) INotifyPropertyChanged 。
定义模型类
public class MyModel: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
string content;
public string Content
{
get
{
return content;
}
set
{
if (content != value)
{
content = value;
OnPropertyChanged("Content");
}
}
}
}
在 View 模型中
public ObservableCollection<MyModel> Addresses { get; set; }
Addresses = new ObservableCollection<MyModel>();
Addresses.Add(new MyModel() {Content = "test1" });
Addresses.Add(new MyModel() { Content = "test2" });
在 xaml 中
<Entry Text="{Binding Content, Mode=TwoWay}" HorizontalOptions="FillAndExpand"/>
关于xaml - Xamarin Forms 中与 ObservableCollection<string> 的两种方式绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63192111/