小编Sje*_*oet的帖子

自定义视图中的 BindableProperty 不会取消订阅 PropertyChanged

背景信息

我正在 XAML 中开发 Xamarin Forms(v4.1.1.3,在 iOS 上测试)应用程序,使用 MVVM 和视图优先方法;我使用 MVVMLight 的 ViewModelLocator 服务将单实例 ViewModel 分配给视图:

BindingContext="{Binding [SearchViewModel], Source={StaticResource ViewModelLocator}}"
Run Code Online (Sandbox Code Playgroud)

当导航到另一个页面时,我正在构建该页面的一个新实例,该实例每次都会收到完全相同的 ViewModel 实例。

var page = new SearchView();
var tabbedPage = Application.Current.MainPage as TabbedPage;
if (tabbedPage != null)
    await tabbedPage.CurrentPage.Navigation.PushAsync(page);
Run Code Online (Sandbox Code Playgroud)

问题

我已经实现了一个自定义控件(视图?),它应该以类似平铺的布局显示搜索结果。该控件是在从搜索导航NavigationPage到搜索结果时创建的ContentPage

每次我返回搜索页面并导航回搜索结果时,都会重建视图并订阅PropertyChanged视图。BindableProperties这些PropertyChanged事件永远不会取消订阅,因此每次我导航到搜索结果视图并更改绑定的 ViewModel 属性时,该事件都会被触发多次。

在以下代码中OnItemsPropertyChanged,根据我从搜索视图导航到搜索结果视图的次数,会多次触发:

public class WrapLayout : Grid
{
    public static readonly BindableProperty ItemsProperty =
        BindableProperty.Create("Items", typeof(IEnumerable), typeof(WrapLayout), null, propertyChanged: OnItemsPropertyChanged);

    public IEnumerable …
Run Code Online (Sandbox Code Playgroud)

c# mvvm xamarin xamarin.forms

5
推荐指数
1
解决办法
960
查看次数

标签 统计

c# ×1

mvvm ×1

xamarin ×1

xamarin.forms ×1