如何将ViewModel列表绑定到自定义控件?

时间:2017-02-08 19:01:23

标签: c# mvvm xamarin.forms prism

我使用Prism开发了一个Xamarin.Form应用程序。我正在创建一个自定义轮播控件:

public class CarouselLayout : ScrollView
{
    public IList ItemsSource
    {
        get
        {
            return (IList)GetValue(ItemsSourceProperty);
        }
        set
        {
            SetValue(ItemsSourceProperty, value);
        }
    }

    public static readonly BindableProperty ItemsSourceProperty =
        BindableProperty.Create(
           nameof(ItemsSource),
           typeof(IList),
           typeof(CarouselLayout),
           null,
           propertyChanged: (bindableObject, oldValue, newValue) =>
           {
               ((CarouselLayout)bindableObject).ItemsSourceChanged();
           }
        );

    void ItemsSourceChanged()
    {
        _stack.Children.Clear();
        foreach (var item in ItemsSource) // ItemSource is a list of ViewModels
        {
            var view = ?; // How to resolve the View for this ViewModel?
            var bindableObject = view as BindableObject;
            if (bindableObject != null)
                bindableObject.BindingContext = item; // Is this the Prism way to do this?
            _stack.Children.Add(view);
        }
    }
}

这是ContentPage的ViewModel

public class MainPageViewModel: BindableBase
{
    private List<BaseViewModel> _viewModels;
    public List<BaseViewModel> ViewModels
    {
        get { return _viewModels; }
        set
        {
            SetProperty(ref _viewModels, value);
            OnPropertyChanged();
        }

    }

    public MainPageViewModel()
    {
        ViewModels = CreateViewModelsList();
    }

    private List<BaseViewModel> CreateViewModelsList()
    {
        return new List<BaseViewModel>{
            new FirstViewModel(),
            new SecondViewModel()
        };
    }
}

这是我在MainPage中创建轮播并绑定ViewModels列表的方法:

var carousel = new CarouselLayout();
[...]
carousel.SetBinding(CarouselLayout.ItemsSourceProperty, "ViewModels");

如何将ViewModel绑定到CarouselLayout的方法ItemsSourceChanged()中的视图?

1 个答案:

答案 0 :(得分:0)

为自定义控件创建一个可绑定属性,以访问控件的zoomIn: { value: function () { var first ; var second ; this.checkCanvasWidth().then(function (width) { first = width console.log("before:" + width); }); //performs a click this.clickZoomIn(); this.checkCanvasWidth().then(function (width) { second = width console.log("after:" + width); }); expect(first).toBeGreaterThan(second); } } 属性。

ItemTemplate

然后你就能做到这样的事情:

public static readonly BindableProperty ItemTemplateProperty =
    BindableProperty.Create(nameof(ItemTemplate), typeof(DataTemplate), typeof(CarouselLayout ), default(DataTemplate));

public DataTemplate ItemTemplate
{
    get { return (DataTemplate)GetValue(ItemTemplateProperty); }
    set { SetValue(ItemTemplateProperty, value); }
}