我有一个 Listbox 并且像这样应用了一个 DataTemplate

<ListBox>
   <ListBox.ItemTemplate>
<Grid>
 <TextBlock Text="{Binding Path=Name}" Grid.Row=0/>
    <ComoboBox Name="test"
            DisplayMemberPath="Country"
            SelectedValuePath="Country_ID">
</Grid>

  1. 如何根据 ListBox 中选择的每个项目动态地将 ItemSource 加载到此 ComboBox ?我刚接触WPF ...请帮助您提出宝贵的建议。
有帮助吗?

解决方案

<ListBox>
  <ListBox.ItemTemplate>
   <Grid>
     <TextBlock Text="{Binding Path=Name}" Grid.Row=0/>
        <ComoboBox Name="test" 
           DataContent="{Binding RelativeSource={RelativeSource AncestorType=ListBox}}"                 
           ItemsSource="{Binding}"
        DisplayMemberPath="Country"
        SelectedValuePath="Country_ID">
   </Grid>

现在,您的组合框始终与父列表框具有相同的项目源。

其他提示

执行此操作的一种方法是将ComboBox的ItemsSource绑定到ListBox的SelectedValue属性。为此,ListBox需要绑定到包含ComboBox将绑定到的项列表的项集合。

<ListBox
    x:Name="CategoryList"
    ItemsSource="{Binding Path=MasterList, 
        RelativeSource={RelativeSource AncestorType=Window}}"
    DisplayMemberPath="MasterProperty"
    SelectedValuePath="Details"
    />

<ComboBox
    ItemsSource="{Binding Path=SelectedValue, ElementName=CategoryList}"
    DisplayMemberPath="DetailProperty"
    Grid.Row="1"
    />

在这个例子中,我在窗口后面的代码中创建了一个公共属性,公开了包含Details集合的对象列表。

public List<Master> MasterList { get; set; }

public class Master
{
    public string MasterProperty { get; set; }
    public List<Detail> Details { get; set; }
}

public class Detail
{
    public string DetailProperty { get; set; }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top