2009-10-30 125 views
0

讓我先描述我的目標:我創建了一個具有3個屬性的對象:開始,結束和時間。我創建的這些特性的8一個ObservableCollection,所以它看起來是這樣的:將集合屬性的顯示值綁定到組合框

//C# 
internal class MyObjects : ObservableCollection<MyObjectSetting> 
     { 
      public MyObjects() 
       : base() 
      { 
       Add(new MyObjectSetting(
          start1, 
          end1, 
          time1); 
       Add(new MyObjectSetting(
          start2, 
          end2, 
          time2); 
    (etc) 
      } 
     } 

我想有結合在這8名對象中列出的各個屬性3個組合框,所以組合框看起來像「啓動1 ,start2,... start8「,」end1,end2,... end8「。

下面的代碼成功地將ComboBox綁定到對象本身,但是我不知道如何訪問每個組合框的單獨屬性。

// WPF 
    <Grid> 
     <Grid.Resources> 
      <local:MyObjects x:Key="myMyObjects"/> 
     </Grid.Resources> 

     <ComboBox x:Name="cbxStartPosition" 
        Grid.Row="0" 
        Grid.Column="3" 
        ItemsSource="{Binding Source={StaticResource myMyObjects}}"     
        > 
    </Grid> 

有人可以幫助我確定如何綁定存儲在集合中的組合框顯示的顯示值對象的屬性?

我已經嘗試添加在MSDN here的ListBoxinvestigating的MultiBinding樣品一個DataTemplate如下圖所示,但接收低於一個錯誤:

//WPF 
     <DataTemplate x:Key="StartPositionTemplate"> 
      <ListBox> 
       <MultiBinding Converter="{StaticResource myNameConverter}"> 
        <Binding Path="FirstName"/> 
        <Binding Path="LastName"/> 
       </MultiBinding> 
      </ListBoxItem> 
     </DataTemplate> 

錯誤32類型的值「的DataTemplate」不能被添加到'UIElementCollection'類型的集合或字典。


此錯誤被觸發是因爲我不在XAML部分。 HTH人在未來。根據下面的答案,使用DataTemplate是一條路。


如果DataTemplate中是不是要走的路,沒有人知道這將是一個更好的方式來處理這個?

回答

2

如果你只是想顯示的屬性的字符串值,你可以使用DisplayMemberPath

<ComboBox ItemsSource="{Binding Source={StaticResource myMyObjects}}" DisplayMemberPath="Start"/> 

對於更復雜的情況下,您可以使用自定義項模板:

<ComboBox ItemsSource="{Binding Source={StaticResource myMyObjects}}"> 
    <ComboBox.ItemTemplate> 
     <DataTemplate> 
      <StackPanel Orientation="Horizontal"> 
       <TextBlock Text="{Binding Start}"/> 
       <TextBlock Text="{Binding End}"/> 
      </StackPanel> 
     </DataTemplate> 
    </ComboBox.ItemTemplate> 
</ComboBox> 
+0

這完全是*我正在尋找的東西。非常感謝你 - 我使用了第二個複雜場景,我將深入研究ItemTemplates以瞭解未來工作的進展情況。做得好! – CrimsonX 2009-10-30 19:34:31