ListBox集合之外的绑定属性

时间:2017-09-14 03:28:07

标签: c# wpf

如果我有一个ListBox并且它已绑定到MyObject.MyCollection,我怎样才能获得MyObject.MyValue

<ListBox ItemsSource="{Binding Path=MyObject.MyCollection}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <StackPanel>
        <TextBlock Text="{Binding Path=Name}"/>
        <TextBlock Text="{Binding Path=MyObject.MyValue}"/>
      </StackPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>
public class MyObject {
   public ObservableCollection<CollectionThing> MyCollection {get; set;}
   public string MyValue {get; set;}
}

1 个答案:

答案 0 :(得分:0)

我认为你可以在绑定中使用相对来源

<ListBox ItemsSource="{Binding Path=MyObject.MyCollection}">
    <ListBox.ItemTemplate>
        <DataTemplate>
             <StackPanel>
                 <TextBlock Text="{Binding Path=Name}"/>
                 <TextBlock Text="{Binding Path=DataContext.MyObject.MyValue,
                                   RelativeSource={RelativeSource AncestorType=ListBox}}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>