【问题标题】:DataContext ComboBox Binding inside of ListBoxListBox 内的 DataContext ComboBox 绑定
【发布时间】:2017-06-05 19:30:05
【问题描述】:

我有一个ListBox,它显示一个List<Item> Items,其中Item 是一个自定义对象。对于每个项目,我希望用户看到 ComboBoxList<string> Options 作为 Source ,所选 Item 绑定到 Item 上的属性。在列表框中,我可以毫无问题地绑定各个 Item 属性,但是如何返回 DataContext 以获取我的选项列表?

View Model 被设置为页面的 DataContext

class ViewModel
{
      public ObservableCollection<string> Options { get; set; }
      public ObservableCollection<Item> Items { get; set; }
}

Xaml

<ListBox x:Name="ItemsListBox" ItemsSource="{Binding Items}">
    <ListBox.ItemTemplate>
         <DataTemplate>
             <Grid Height="50" >
                 <Grid.ColumnDefinitions>
                     <ColumnDefinition Width="*"/>
                     <ColumnDefinition Width="*"/> 
                 </Grid.ColumnDefinitions>
                 <TextBlock x:Name="ItemProperty1TB" 
                     Text="{Binding Path=Property1, Mode=OneWay}"
                     Grid.Column="0" 
                 />
                 <ComboBox x:Name="OptionsCB" 
                     SelectedItem ="{Binding ChosenOptions, Mode=TwoWay}" 
                     ItemsSource="{Binding Path=DataContext.Options}"          
                     Grid.Column="1" 
                     PlaceholderText="Option"
                 />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

我试图删掉尽可能多的额外代码并获得一个可读的示例。

How to bind to a source inside a ListBox different from the ItemsSource already specified这使用了不存在的AncestorType?

ComboBox inside Listbox.ItemTemplate Binding problem 这绑定到一个静态资源。我应该将我的选项放入静态资源中吗?

ElementName 看起来很有希望,但我的 IDE 只推荐使用 ListBox 内的元素...不要相信 VISUAL STUDIO

我只是说这一切都错了吗?

【问题讨论】:

  • ViewModel 需要有属性,而不是字段。这是实际的代码吗?
  • 不,这不是实际的代码,我会很快改变
  • 试试ItemsSource="{Binding Path=DataContext.Options, ElementName=ItemsListBox}"
  • @EdPlunkett 谢谢它成功了!!!!!当我第一次查看该选项时,IDE 仅推荐该 ListBox 内的元素,因此我认为它是本地范围的。我不应该信任 Visual Studio
  • 哈!当你更新你的评论时,我正要告诉你永远不要相信 VS!

标签: c# xaml data-binding windows-phone-8.1


【解决方案1】:

试试这个:

ItemsSource="{Binding Path=DataContext.Options, ElementName=ItemsListBox}" 

【讨论】:

    【解决方案2】:

    您可以使用 Combobox 绑定对象上的 RelativeSource 属性来查找父对象。像这样的东西应该可以工作

    ItemsSource="{Binding Path=DataContext.Options, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"
    

    如果您为此使用 Page 或 Window,请将 UserControl 替换为 Page。

    【讨论】:

    • 该方法似乎在 WPF 中有效,但在 windows phone 中无效。
    • 好的,我不确定 windows phone 但你可以在你的父母上使用 ElementName 如果它在 wp 中有效。
    猜你喜欢
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多