【问题标题】:Binding properties outside ListBox collection [duplicate]ListBox集合之外的绑定属性[重复]
【发布时间】:2018-02-22 21:41:03
【问题描述】:

如果我有一个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;}
}

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

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

    <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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      • 1970-01-01
      • 2015-04-15
      • 1970-01-01
      相关资源
      最近更新 更多