【问题标题】:WPF - Binding a variable in an already bound ListBox?WPF - 在已绑定的 ListBox 中绑定变量?
【发布时间】:2010-06-11 20:22:20
【问题描述】:

我真的不知道如何为这个问题命名,但我需要一些帮助来绑定到 ListBox。

我有一个对象,它包含(以及其他信息)需要绑定在一个 ListBox 中的 2 个属性。其中一个是对象的 ObservableCollection,称为 Layers,另一个属性包含 Point、Line 或 Polygon 的枚举值,称为 SpatialType。这些将作为地图应用程序的图例。我已经将图层绑定到列表框,没问题,但是在 ListBox.ItemTemplate 内部,我需要将单个变量 SpatialType 绑定到列表框中的每个项目。我遇到的问题是,当我尝试在 ListBox 内进行绑定时,我可以访问的唯一变量是每个图层的属性,并且我无法访问包含图层的原始绑定类的任何属性(以及所需的 SpatialType 属性)。

如何才能在不破坏良好的 MVVM 架构的情况下将这条信息绑定到 ItemTemplate 中?

【问题讨论】:

    标签: data-binding binding


    【解决方案1】:

    您可以在您的视图中拥有一个作为数据上下文基础的 ObjectDataProvider,并让 ObjectInstance 指向您的视图模型。然后你可以像这样从 ItemTemplate 绑定:

    <UserControl.Resources>
         <ObjectDataProvider x:Key="Data"/>
         <DataTemplate x:Key="Template">
             <TextBlock Text="{Binding SpatialType,Source={StaticResource Data}}/>
         </DataTemplate>
    </UserControl.Resources>
    <Grid DataContext={Binding Source={StaticResource Data}}>
         <ListBox ItemsSource="{Binding Layers}" ItemTemplate="{StaticResource Template}"/>
    </Grid>
    

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      我最终做的是使用 FindAncestor 在绑定中获取更高“层”的 DataContext:

      Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, Path=DataContext.LayerSymbolization.SpatialType, Mode=TwoWay}"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-01
        • 2014-05-17
        • 2012-06-11
        相关资源
        最近更新 更多