2

我正在尝试将下面的 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;
       }
    }
4

2 回答 2

2

DataContextTabControl类型MainVM。绑定的不应该是 ,RelativeSource而应该是。ComboBoxTabControlListBox

于 2013-01-16T14:01:27.593 回答
0

您的InvCharacters属性位于您的TextEditorVM对象上ObservableCollection,但您的绑定是引用的TabControl.DataContext,它是 MainVM,并且不包含该属性。

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

<ComboBox ItemsSource="{Binding DataContext.InvCharacters, 
              RelativeSource={RelativeSource AncestorType={x:Type TabItem}}}">
</ComboBox>
于 2013-01-16T14:45:38.027 回答