gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:11:49 25 4
gpt4 key购买 nike

我有两个用户控件,第一个带有一个列表框,该列表框绑定(bind)到客户列表,显示每个客户的一些简单详细信息。

第二个用户控件我希望获得第一个用户控件的列表框中选择的客户的更详细 View 。

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

我的列表框:

            <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>

详细 View 用户控件(到目前为止)

 <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>

谢谢格雷格

最佳答案

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

<ListBox Name="lstCustomer" ItemsSource="{Binding Customers}"
SelectedItem = "{Binding SelectedCustomer}" >
. . . . .
</ListBox>

既然您提到两个用户控件都在同一 View 中,所以我假设它们共享相同的 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>

关于WPF - 绑定(bind)到用户控件之间列表框的选定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6874662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com