在Wpf中正确绑定DataTemplate中的Combobox

时间:2013-01-16 13:46:08

标签: wpf data-binding combobox

我正在尝试将下面的ComboBox绑定到ObservableCollection中的字符列表,但它不会显示任何内容。有什么想法吗?

XAML:

    <TabControl ItemsSource ="{Binding TextEditors}"
     <TabControl.ContentTemplate>
      <DataTemplate>
       <ListBox> ItemsSource="{Binding TextLines}"
        <ListBox.ItemTemplate>
         <DataTemplate>
          <Grid>


               <ComboBox 
                   ItemsSource="{Binding DataContext.InvCharacter, RelativeSource={RelativeSource AncestorType={x:Type TabItem}}}" 
                   DisplayMemberPath="name" 
                   SelectedValuePath="cid" 
                   SelectedValue="{Binding cid}">
               </ComboBox>


          </Grid>
         </DataTemplate>
        </ListBox.ItemTemplate>
       </ListBox>
      </DataTemplate>
     </TabControl.ContentTemplate>
    </TabControl>

这是我所指的课程:

     class TextEditorVM: IViewModel {
         public ObservableCollection<TextLineVM> TextLines { get { return textLines; } set { textLines = value;} }
         public ObservableCollection<T_Character> InvCharacters { get { return invCharacters; } set { invCharacters = value; } }


         public TextEditorVM(T_Dialogue dialogue)
         {

             DialogueManager.Instance.Register(this);
             this.TextLines = new ObservableCollection<TextLineVM>();
             this.InvCharacters = new ObservableCollection<T_Character>();
         }
    }

和MainVM:

     class MainVM : IViewModel
     {
           public ObservableCollection<TextEditorVM> TextEditors { get { return textEditors; } set { textEditors = value; OnPropertyChanged("TextEditors"); } 
     }

我的T_Character类现在看起来像这样:

    public class T_Character
    {

       public String cid { get; set; }
       public String name { get; set; }

       public T_Character(String cid, String name)
       {
          this.cid = cid;
          this.name = name;
       }
    }

2 个答案:

答案 0 :(得分:2)

DataContext的{​​{1}}属于TabControl类型。 MainVM绑定的RelativeSource不应该是ComboBox,而是TabControl

答案 1 :(得分:0)

您的InvCharacters媒体资源位于您TextEditorVM的{​​{1}}对象上,但您的绑定引用了ObservableCollection TabControl.DataContext,并且不包含该属性。

将您的RelativeSource绑定切换为引用MainVM(绑定TabItem时自动创建)或TabControl.ItemsSource引用您的ListBox对象

TextEditorVM