控件,如ListBox
有ItemsSource
屬性,它可以綁定到如何安置的ItemsSource和項目
<ListBox x:Name="ListBoxColours" ItemsSource="{Binding Colours}" />
它也有一個Items
財產然而,它可以被用來在背後
ListBoxColours.Items.Add("Red");
我創建其必須在ListBox
一個CustomControl,我已經在我的控制曝光的ItemSource
允許用戶綁定在自己的項目屬性。
<ListBox
x:Name="PART_ListBox"
ItemsSource="{Binding ItemsSource, RelativeSource={RelativeSource AncestorType=local:TextBoxComboControl}}"
SelectionMode="Single" />
...
public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register(
"ItemsSource", typeof(IEnumerable), typeof(TextBoxComboControl), new PropertyMetadata(default(IEnumerable)));
public IEnumerable ItemsSource
{
get { return (IEnumerable) GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
...
<local:TextBoxComboControl ItemsSource="{Binding Colours}" />
我想補充的能力,爲用戶在代碼中添加項目背後還有,雖然,他們櫃面不想使用綁定。我想知道如何與其他人互動。爲了讓他們使用peoprty,我必須將ListBox
項目綁定到我控制的兩個屬性中。
從[Items]的註釋部分(https://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.items(v = vs.110))。aspx)page:*請注意,您使用Items或ItemsSource屬性來指定應該用於生成ItemsControl內容的集合。當ItemsSource屬性被設置時,Items集合被設置爲只讀和固定大小。* – Clemens
其實,我會說你只需要「中繼」這個屬性。 '... Items {get => PART_ListBox.Items; set => PART_ListBox.Items = value; }'... – Fildor
@Fildor請注意,Items是隻讀屬性。 – Clemens