WPF - 绑定到用户控件之间列表框的选择项

gr-*_*-eg 8 data-binding wpf user-controls listbox selecteditem

我有两个用户控件,第一个带有一个列表框,该列表框绑定到一个客户列表,显示每个客户的一些简单细节.

第二个用户控件我想更详细地查看在第一个usercontrol的列表框中选择的客户.

是否可以在第二个控件中设置绑定以绑定到第一个用户控件中的选定项?

我的列表框:

            <ListBox Name="lstCustomer" ItemsSource="{Binding Customers}" >           
                <ListBox.Resources>

                    <DataTemplate DataType="{x:Type MyApplication:Customers}">
                       <Label Grid.Row="0" Content="{Binding Customer.name}" FontSize="14" FontWeight="Bold" Padding="5" />                             
                                <Label Grid.Row="1" Grid.Column="0" Content="{Binding Customer.telephone}" Padding="10,5" />                 
                            </Grid>
                        </Grid>

                    </DataTemplate>
                </ListBox.Resources>
            </ListBox>
Run Code Online (Sandbox Code Playgroud)

详细视图Usercontrol(迄今为止)

 <Grid x:Name="containingGrid" DataContext="{Binding ElementName=lstCustomers, Path=SelectedItem}">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
            <TextBlock Text="{Binding Customer.name}" FontSize="23"/>
        </Grid>
Run Code Online (Sandbox Code Playgroud)

谢谢格雷格

Roh*_*ats 4

我建议在 Customer 对象的 ViewModel 中有一个属性,例如 SelectedCustomer 并将其绑定到列表框的 SelectedItem,如下所示 -

<ListBox Name="lstCustomer" ItemsSource="{Binding Customers}"
                            SelectedItem = "{Binding SelectedCustomer}" >           
               . . . . .
 </ListBox>
Run Code Online (Sandbox Code Playgroud)

由于您提到两个用户控件都在同一视图中,所以我假设它们共享相同的 ViewModel。在这种情况下,您可以简单地这样设置数据上下文 -

<Grid x:Name="containingGrid" DataContext="{Binding SelectedCustomer}">
  <Grid.RowDefinitions>
       <RowDefinition Height="Auto"/>
       <RowDefinition Height="Auto"/>
       <RowDefinition Height="Auto"/>
   </Grid.RowDefinitions>
   <Grid.ColumnDefinitions>
       <ColumnDefinition Width="Auto"/>
       <ColumnDefinition Width="Auto"/>
   </Grid.ColumnDefinitions>
   <TextBlock Text="{Binding Name}" FontSize="23"/>
</Grid> 
Run Code Online (Sandbox Code Playgroud)