如何将ObservableCollection正确绑定到Custom Control属性?

时间:2019-05-21 14:29:26

标签: c# xamarin.forms

我创建了一个自定义控件,该控件具有一些要绑定的属性,在我的情况下,只是使控件本身不可见,而另一个控件则传递先前填充的ObservableCollection来创建控件内容。

第一个可以完美工作,但是即使我将它添加到XAML中,ObservableCollection也不能正确绑定。

这是我在使其可见后尝试在队列控件中对其进行迭代的结果:

https://i.imgur.com/dddFoWu.png

我做错了什么?

先谢谢了。

这是我的财产:

public static readonly BindableProperty ContractsListProperty = BindableProperty.Create(nameof(ContractList), typeof(ObservableCollection<object>), typeof(PrivacyControl), new ObservableCollection<object>(), BindingMode.TwoWay, propertyChanged: ContractListPropertyChangedDelegate);
public ObservableCollection<object> ContractList 
{
            get => 
(ObservableCollection<object>)GetValue(ContractsListProperty);
            set => SetValue(ContractsListProperty, value);
}

这是我在XAML中的控件:

<controls:PrivacyControl IsPrivacyVisible="{Binding IsPrivacyStackVisible}" ContractList="{Binding CardsAndLoansList}" />

已编辑:

这是我的VM,我在其中检查卡片/贷款并将其添加到ObservableCollection<object>,“ CardsAndLoans”也已在ctor中初始化。

private ObservableCollection<object> cardsAndLoansList;
public ObservableCollection<object> CardsAndLoansList
{
get => cardsAndLoansList;
set { cardsAndLoansList = value; RaisePropertyChanged(); }
}

private async Task InitUserInfoAndPrivacy()
{
            CardsAndLoansList.Clear();

            await InitUserInformation();

            var hasLoans = GlobalSettings.Loans.NotNullOrEmpty();
            if (hasLoans)
            {
                foreach (var loan in GlobalSettings.Loans)
                    CardsAndLoansList.Add(loan);
            }

            ExampleList = CardsAndLoansList.ToList(); //<=== This is from an another try with List<obj>. 

            IsPrivacyStackVisible = UserData.ContractList.NotNullOrEmpty() || hasLoans;
}

2 个答案:

答案 0 :(得分:1)

似乎有错字。 BindableProperty称为ContractsListProperty,而属性本身称为ContractList(缺少s)。将其更改为ContractsList,它应该可以工作(BindableProperty名称必须是属性的名称+“属性”)

希望这会有所帮助

答案 1 :(得分:0)

您需要给自定义控件命名,然后将源引用添加到Xaml中的绑定属性。例如,

顶部xaml标记应具有名称,

<ContentView
xmlns:forms="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.Core" xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="Sample.Controls.List"
         x:Name="listControl">

,然后在绑定属性时,如下所示添加源引用,

<ListView  IsVisible="{Binding IsPrivacyVisible, Source={x:Reference listControl}}" ItemSource="{Binding ContractList, Source={x:Reference listControl}}" >
相关问题