【问题标题】:Set different binding context for custom user control为自定义用户控件设置不同的绑定上下文
【发布时间】:2015-10-08 03:32:59
【问题描述】:

我正在尝试创建我的第一个 Xamarin.Forms 自定义用户控件,名为 LocationSelector。它有一个Entry,当用户输入一些东西时,会显示一个带有可选位置的列表(类似于谷歌地图中的选择)。

所选位置是控件的重要“返回值”。 我的计划是捕获列表的ItemSelected 事件并设置SelectedLocation 属性。 LocationSelector 被设计为 MVVM,因为到目前为止一切正常,只是代码隐藏(我认为这足以描述问题):

public partial class LocationSelector : StackLayout
{
    public static readonly BindableProperty SelectedLocationProperty =
      BindableProperty.Create<LocationSelector, LocationModel>(s => s.SelectedLocation, new LocationModel(), BindingMode.TwoWay);

    public LocationSelector()
    {
        InitializeComponent();
        var model = new LocationSelectorModel();
        BindingContext = model;

        _listView.ItemSelected += (sender, args) =>
        {
            SelectedLocation = model.SelectedLocation;
        };
    }

    public LocationModel SelectedLocation
    {
        get { return (LocationModel)GetValue(SelectedLocationProperty); }
        set { SetValue(SelectedLocationProperty, value); }
    }
}

现在我想在 BindingContext 设置为 SearchViewModel 的搜索视图上使用此控件:

<ContentPage x:Class="Application.App.Views.SearchView" ...>
    <c:LocationSelector SelectedLocation="{Binding Location}"/>
</ContentPage>

public class SearchViewModel : ViewModel
{
    private LocationModel _location;
    public LocationModel Location
    {
        get { return _location; }
        set { SetProperty(ref _location, value); }
    }       
}

不幸的是,这不起作用。输出抛出绑定警告:

绑定:在“Application.App.CustomControls.LocationSelectorModel”上找不到“Location”属性,目标属性:“Application.App.CustomControls.LocationSelector.SelectedLocation”

为什么将绑定指向在我的自定义控件“内部”使用的 ViewModel 中的属性,而不是指向视图的 BindingContext 中的属性?

【问题讨论】:

  • 在 LocationSelector() 构造函数中,您将 Bi​​ndingContext 显式设置为 LocationSelectorModel 的实例。
  • 这就是我害怕的。这是否意味着我无法创建 MVVM 样式的用户控件?
  • 标准控件并不是每个都有自己的 ViewModel。他们只有一个 BindingContext。您的控件应该通过属性获取它的 BindingContext,或者从它的父级继承。
  • 这听起来对我来说是一个很大的限制。因为所以我无法编写独立工作的用户控件。例如,在我的情况下,带有建议和一些可见标志的列表在用户控件中非常重要,我不想在每次使用控件时都关心它们。但也许到目前为止我还没有理解自定义用户控件的概念。或者我需要用代码而不是 XAML 和代码来完整地编写它们(我想这会起作用)?!
  • 如果您的控件中有一些元素需要绑定到某些硬编码(或内部)值,而其他元素需要绑定到控件的外部绑定上下文,您可以这样做,您将只需要使用多个绑定上下文。

标签: xamarin xamarin.forms


【解决方案1】:

问题是将BindingContext设置为用户控件的视图模型:

public LocationSelector()
{
    var model = new LocationSelectorModel();
    BindingContext = model; // this causes the problem
    // ...
}

this 帖子中,我找到了解决方案。将BindingContext 设置为每个子元素而不是整个用户控件正在完成这项工作:

public LocationSelector()
{
    var model = new LocationSelectorModel();
    foreach (var child in Children)
    {
        child.BindingContext = model;
    }
}

【讨论】:

    猜你喜欢
    • 2012-04-01
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 2021-11-02
    相关资源
    最近更新 更多