2017-03-01 83 views
1

我想弄清楚如何綁定ListBoxItems列表,並讓我的控件上顯示正確的DisplayMemberPath。我需要的,如果我在的ItemsSource綁定到國家爲ListBoxItem的內容設置DisplayMemberPath

public class State 
{ 
    public string LongName { get; set; } 
    public string ShortName { get; set; } 
} 

的名單我有一個AllItems,國家的列表中使用ListBoxItems的名單,因爲我的控制訪問屬性如的ActualHeight /寬,這是我輸了。我正在填充我的ListBox的ItemsSource,如下所示:

BoxItems = new ObservableCollection<MyListBoxItem>(AllItems.Select(i => new MyListBoxItem() { Content = i }).ToList()); 

我希望我的DisplayMemberPath是LongName。我嘗試了很多不同的方式來修改.xaml以正確顯示LongName(紐約,新澤西,佛羅里達等),但我總是以listpace.classname結尾。我試圖在.xaml和.xaml.cs中設置ListBox的DisplayMemberPath和ItemsSource。

我已經嘗試了很多不同的東西,例如設置內容控件並在.xaml中添加數據模板。

+0

'Content = i.LongName' – AnjumSKhan

+0

我想做一個通用控件,它需要一個'List ',所以我不會知道這些字段的名稱。我公開了另一個屬性,我使用它來設置DisplayMemberPath。 – user7643143

回答

1

創建ObservableCollection<MyListBoxItem>似乎沒有道理。

直接更好的結合到AllItems:在IEnumerable<T>的ItemsSource

<ListBox ItemsSource="{Binding AllItems}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <TextBlock Text="{Binding LongName}"/> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 
+0

在上面的代碼片段中,它應該只是'ListBoxItem',而不是'MyListBoxItem'。我需要使用ListBoxItems,因爲它們公開了我在控件中使用的其他位置的Height/Width(ActualHeight和ActualWidth)屬性。如果我僅僅綁定一個'List ',我就會失去這些屬性。 – user7643143

+0

DataTemplate中的元素也有一個大小。你可以通過ListBox的'ItemContainerGenerator.ContainerFromItem'方法得到一個包含數據項的ListBoxItem。 – Clemens

+0

有時這會返回null,即使itemource存在於itemsource中。 – user7643143

0

DisplayMemberPath指型T的屬性:

<ListBox ItemsSource="{Binding AllItems}" 
     DisplayMemberPath="LongName"/> 

而不是設置DisplayMemberPath,你可以將ItemTemplate屬性設置的ListBox。因此,如果將ItemsSource設置爲ObservableCollection<MyListBoxItem>,則012xx類必須具有LongName屬性,以便您能夠將DisplayMemberPath屬性設置爲「LongName」。

我需要使用ListBoxItems列表,因爲我的控件正在訪問諸如ActualHeight/Width之類的屬性,如果將ItemsSource綁定到狀態列表,則會失去這些屬性。

您添加到Items/ItemsSource屬性,是不是ListBoxItem被隱式裹在ListBoxItem容器中的任何項目。您可以使用ListBoxItemContainerStyle屬性來設置該屬性的任何屬性。這意味着,你可以在State類和綁定添加HeightWidth屬性,這些前提是你設置的ItemsSourceIEnumerable<State>

<ListBox x:Name="lb" ItemsSource="{Binding AllItems}" DisplayMemberPath="LongName" Loaded="ListBox_Loaded"> 
    <ListBox.ItemContainerStyle> 
     <Style TargetType="ListBoxItem"> 
      <Setter Property="Height" Value="{Binding Height}" /> 
     </Style> 
    </ListBox.ItemContainerStyle> 
</ListBox> 

你也可以得到一個參考這樣的容器一旦被加載,使用ItemContainerGenerator

private void ListBox_Loaded(object sender, RoutedEventArgs e) 
{ 
    foreach (var item in lb.Items) 
    { 
     var container = lb.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem; 
     if (container != null) 
     { 
      //... 
     } 
    } 
} 

設置的ItemsSource到IEnumerable<ListBoxItem>是不是一個好主意。