发布:2021/10/21 10:23:25作者:管理员 来源:本站 浏览次数:988
实体对象定义Model2 和Model均可 实现响应效果
public class BaseModel : INotifyPropertyChanged
{
private bool _selected;
public bool Selected
{
get { return _selected; }
set
{
if (Selected != value)
{
_selected = value;
OnPropertyChanged();
OnPropertyChanged("StatusFormat");
}
}
}
public string StatusFormat
{
get
{
return Selected ? "选中了" : "没选中";
}
}
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class BaseModel2 : BindableObject
{
public static readonly BindableProperty SelectedProperty =
BindableProperty.Create("Selected",
typeof(bool),
typeof(bool),
false
);
public bool Selected
{
get
{
return (bool)this.GetValue(SelectedProperty);
}
set
{
if (Selected != value)
{
this.SetValue(SelectedProperty, value);
//通知下另外的依赖属性跟着变
OnPropertyChanged("StatusFormat");
}
}
}
public string StatusFormat
{
get
{
return Selected ? "选中了" : "没选中";
}
}
}
public partial class MainPage : ContentPage
{
/// <summary>
/// 我实现了2个mvvm方式 BaseModel 和 BaseModel2 都可以实现响应
/// </summary>
private ObservableCollection<BaseModel2> Models;
public int Tick { get; set; }
public MainPage()
{
InitializeComponent();
Models = new ObservableCollection<BaseModel2>();
lst.ItemsSource = Models;
this.BindingContext = this;
}
private void Button_Clicked(object sender, EventArgs e)
{
Tick++;
this.OnPropertyChanged("Tick");
if (Models.Count==0)
{
Models.Add(new BaseModel2 { Selected = false });
Models.Add(new BaseModel2 { Selected = true });
Models.Add(new BaseModel2 { Selected = true });
Models.Add(new BaseModel2 { Selected = false });
}
Models[new Random().Next(Models.Count)].Selected = !Models[new Random().Next(Models.Count)].Selected;
}
}
<?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:local="clr-namespace:App5Mvvm"
x:Class="App5Mvvm.MainPage">
<StackLayout>
<!-- Place new controls here -->
<Label Text="Xamarin MVVM哪些事"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" />
<Label Text="{Binding Tick, StringFormat='{0}次点击'}}"></Label>
<Button Clicked="Button_Clicked" Text="点我点我"></Button>
<ListView x:Name="lst">
<ListView.ItemTemplate>
<DataTemplate >
<ViewCell>
<StackLayout Orientation="Horizontal">
<BoxView WidthRequest="22" Color="Red" IsVisible="{Binding Selected}"></BoxView>
<Label Text="{Binding StatusFormat}"></Label>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4