繁体   English   中英

ListBox内部的DataContext ComboBox绑定

[英]DataContext ComboBox Binding inside of ListBox

我有一个ListBox ,显示一个List<Item> Items其中Item是一个自定义对象。 对于Foreach项,我希望用户看到具有List<string> OptionsComboBox作为源,并且选定的Item绑定到Item的属性。 在列表框中,我可以轻松绑定各个Item属性,但是如何回到DataContext中以获得选项列表呢?

视图模型被设置为页面的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>

我试图削减尽可能多的额外代码并得到一个可读的示例。

如何绑定到与已指定的ItemsSource不同的ListBox内的源 ?这使用不存在的AncestorType?

Listbox.ItemTemplate内的ComboBox绑定问题这绑定到静态资源。 我应该将选项放入静态资源吗?

ElementName看起来很有前途,但我的IDE仅建议Element范围限制在ListBox内... 不要信任可视工作室

我只是想解决所有这些错误吗?

尝试这个:

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

您可以使用Combobox绑定对象上的RelativeSource属性找到父对象。 这样的事情应该工作

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

如果您要使用Page或Window则将UserControl替换为Page。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM