C# 如何停止列表框';s ItemsSource在其绑定源变为空时是否被清除?
背景: 考虑以下XAML片段:C# 如何停止列表框';s ItemsSource在其绑定源变为空时是否被清除?,c#,wpf,xaml,data-binding,C#,Wpf,Xaml,Data Binding,背景: 考虑以下XAML片段: <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="100"/> </Grid.RowDefinitions> <DataGrid Grid.Row="0" x:Name="dataGrid"
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="100"/>
</Grid.RowDefinitions>
<DataGrid
Grid.Row="0"
x:Name="dataGrid"
AutoGenerateColumns="False"
ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=Bobs}"
>
<DataGrid.Columns>
<DataGridTextColumn
Header="Name"
Binding="{Binding Name}"
MinWidth="75"
/>
</DataGrid.Columns>
</DataGrid>
<ListBox
Grid.Row="1"
x:Name="listBox"
DisplayMemberPath="Name"
ItemsSource="{Binding ElementName=dataGrid, Path=SelectedItem.Regions}"
SelectionMode="Multiple"
>
<Interactivity:Interaction.Behaviors>
<ListBoxBehaviors:SynchronizeSelectedItemsBehavior Selections="{Binding ElementName=dataGrid, Path=SelectedItem.SelectedRegions}"/>
</Interactivity:Interaction.Behaviors>
</ListBox>
</Grid>
假设我有一个单独的控件,当切换时,它将网格的IsEnabled属性设置为false。这样做会禁用网格中的DataGrid和ListBox控件
在.NET4.0中,禁用DataGrid的一个不幸的副作用是,它的SelectedItem丢失了。这会产生触发ListBox的ItemsSource绑定的副作用,导致ItemsSource被清除,因为dataGrid的SelectedItem已变为null
问题:
如何更改绑定或更改XAML,以便在dataGrid的SelectedItem变为null时,不会清除ListBox的items集合
附录:
如果datagrid被禁用,您是否可以将所选项目引用存储在某个临时位置?我已经考虑了缓存SelectedItem并在以后恢复它的解决方案。问题是,当SelectedItem变为null时,ItemsSource绑定被清除。因此,虽然我可以在那之后恢复SelectedItem,但已经太晚了。只是想一想,你不能避免禁用datagrid吗。您可以通过触发一些触发器将网格单元格设置为只读。在上面代码段表示的应用程序中,确实需要禁用DataGrid。