【发布时间】:2017-01-17 08:35:27
【问题描述】:
我有以下 TabControl:
<TabControl Name="tabControl" Grid.Row="0" MinWidth="270" HorizontalAlignment="Stretch" ItemsSource="{Binding Counters}" ContentTemplate="{StaticResource templateForTheContent}"
ItemTemplate="{StaticResource templateForTheHeader}">
</TabControl>
它使用这个 DataTemplate:
<Window.Resources>
<DataTemplate x:Key="templateForTheContent" >
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ListBox Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0"
ItemsSource="{Binding}"
SelectionMode="Multiple"
BorderThickness="1" BorderBrush="#FF8B8B8B" SelectionChanged="ListBox_SelectionChanged_1">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<Run Text="{Binding CounterName, Mode=OneWay}" />
<Run Text="{Binding InstanceName, Mode=OneWay}" />
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Name="RAMSelectAllButton" Margin="0,10,0,0" Grid.Column="0" Grid.Row="1">
<TextBlock Text="SELECT ALL"/>
</Button>
<Button Name="RAMUnSelectAllButton" Margin="0,10,0,0" Grid.Column="1" Grid.Row="1">
<TextBlock Text="UNSELECT ALL"/>
</Button>
</Grid>
</DataTemplate>
<DataTemplate x:Key="templateForTheHeader" >
<TextBlock Text="{Binding CategoryName}"/>
</DataTemplate>
</Window.Resources>
它按预期工作,绑定工作良好,如果不存在此问题,一切都会很好: 每次我在 TabControl 中切换一个选项卡时,我之前的选项卡中的 ListBox 的选定项目都会被重置 - 所以当我返回该选项卡时 - 没有选择任何内容。
如何解决这个问题?
//编辑 这是我的 ListBox_SelectionChanged_1 方法:
private void ListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
System.Windows.Controls.ListBox listBoxTemp = sender as System.Windows.Controls.ListBox;
PerformanceCounter counterTemp = (PerformanceCounter)listBoxTemp.Items[0];
if (!appData.SelectedCounters.ContainsKey(counterTemp.CategoryName))
appData.SelectedCounters.Add(counterTemp.CategoryName, new List<PerformanceCounter>());
appData.SelectedCounters[counterTemp.CategoryName].Clear();
foreach (PerformanceCounter counter in listBoxTemp.SelectedItems)
{
appData.SelectedCounters[counterTemp.CategoryName].Add(counter);
}
}
ListBox 绑定到 Counters,也就是 Observable Collection:
public ObservableCollection<ObservableCollection<PerformanceCounter>> Counters
{
get { return _Counters; }
}
ObservableCollection<ObservableCollection<PerformanceCounter>> _Counters = new ObservableCollection<ObservableCollection<PerformanceCounter>>();
【问题讨论】:
-
如果我可以在当前选定的选项卡中访问 ListBox,我将能够处理这个问题。怎么做?我试过 IEnumerable
listBoxList = tabControl.FindChildren ();,但它是空的(虽然有一个 ListBox) -
将 ListBox 绑定到集合后,您将无法从后面的代码中的 Items 访问 IsSelected 属性。您必须通过与 ViewModel 的相应属性绑定来管理它
-
我使用了列表框。所选项目
标签: c# wpf xaml listbox tabcontrol