在ObservableCollection中绑定ObservableCollection

时间:2015-08-14 20:38:41

标签: c# wpf xaml

我刚学会了如何将ComboBox绑定到ObservableCollection。呜啊!有没有办法将第二个ComboBox绑定到第一个ComboBox的选定集合?所以每个Item都有一个ObservableCollection of Peices。当你选择一个Item时,我希望第二个ComboBox显示所选的Item's Peices!

// strong reference, FreeNotification():

function foo() : boolean
var
  Mycon : TMyConnection
  MyQuery : TMyQuery
begin
  Mycon := TMyConnection.Create(nil); // <-- MyCon.RefCnt is now 1
  Mycon.ConnectString := MyConnection1.ConnectString;
  Mycon.ConnectionTimeout:= 3;
  MyQuery := TMyQuery.Create(nil); // <-- MyQuery.RefCnt is now 1
  MyQuery.Connection := Mycon; // <-- MyCon.RefCnt is now 3, MyQuery.RefCnt is now 2
  try
    Mycon.Connect;
    *Do a few Queries*
  finally
    MyQuery.Connection := nil; // <-- MyCon.RefCnt drops to 1, MyQuery.RefCnt drops to 1
  end;
end; // <-- MyCon.RefCnt drops to 0, MyQuery.RefCnt drops to 0, OK!

更新:好的,所以Items是&#39; Item&#39;的列表。物品有一个&#39; Peice&#39;的列表。我希望组合框2显示所选项目的Peices集合的内容。

3 个答案:

答案 0 :(得分:2)

绑定到第一个组合框的选定项目,如下所示:

<ComboBox x:Name="comboBox1" ItemsSource="{Binding Items}" Width="150" Height="30" DisplayMemberPath="Name"></ComboBox>
<ComboBox ItemsSource="{Binding SelectedItem.Peices, ElementName=comboBox1}" Width="150" Height="30" DisplayMemberPath="Name"></ComboBox>

答案 1 :(得分:0)

只需将两者绑定到同一个东西,但添加双向绑定模式。所以:

<Grid>
    <ComboBox x:Name="cbItems" ItemsSource="{Binding Items, Mode=TwoWay, 
                UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="Name" 
                HorizontalAlignment="Left" Height="23" Margin="10,10,0,0" 
                VerticalAlignment="Top" Width="120"/>
    <Button x:Name="button" Content="Add" HorizontalAlignment="Left" Margin="55,33,0,0" 
                VerticalAlignment="Top" Width="75" Click="AddItem"/>

    <ComboBox x:Name="cbPeices" ItemsSource="{Binding Items, Mode=TwoWay,
                    UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="Name" 
                HorizontalAlignment="Left" Margin="10,72,0,0" VerticalAlignment="Top" 
                Width="120"/>
    <Button x:Name="button1" Content="Add" HorizontalAlignment="Left" Margin="55,94,0,0" 
                VerticalAlignment="Top" Width="75"/>
</Grid>

答案 2 :(得分:0)

试试这个,

<ComboBox x:Name="cbItems" ItemsSource="{Binding Items, Mode=TwoWay, 
            UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="Name" 
            HorizontalAlignment="Left" Height="23" Margin="10,10,0,0" 
            VerticalAlignment="Top" Width="120"/>


<ComboBox x:Name="cbPeices" ItemsSource="{Binding Items, Mode=TwoWay,
                UpdateSourceTrigger=PropertyChanged}" 
          DisplayMemberPath="Name" SelectedItem="{Binding ElementName=cbItems, Path=SelectedItem}"
            HorizontalAlignment="Left" Margin="10,72,0,0" VerticalAlignment="Top" 
            Width="120"/>