We are working on field chooser and used custom code to get the search functionality in field chooser of xamDataGrid. We used a Text box to search and a List box to keep the fields of field chooser. The Code that we have used:
<StackPanel>
<TextBox TextChanged="TextBox_TextChanged" />
<ListBox x:Name="PART_FieldsListBox" ItemsSource="{TemplateBinding CurrentFields}" SelectionMode="Single" SelectedItem="{Binding Path=SelectedField, RelativeSource={x:Static RelativeSource.TemplatedParent}, Mode=TwoWay}" HorizontalContentAlignment="Stretch">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.InputBindings>
<KeyBinding Key="Space" Command="{x:Static igDP:FieldChooserCommands.ToggleVisibility}"/>
</ListBox.InputBindings>
</ListBox>
I know the problem is Stack panel. But due to text search code, we cannot remove stack panel. Code for search we used:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
ListBox lb = (((sender as TextBox).Parent as StackPanel).Children[1] as ListBox);
foreach (var item in lb.ItemsSource as ReadOnlyObservableCollection<FieldChooserEntry>)
{
ListBoxItem listBoxItem = (lb.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem);
if ((sender as TextBox).Text.ToString() != "")
{
if (item.Field.Label.ToString().ToLower().Contains((sender as TextBox).Text.ToLower()))
listBoxItem.Visibility = Visibility.Visible;
else
listBoxItem.Visibility = Visibility.Collapsed;
}
else
listBoxItem.Visibility = Visibility.Visible;
}
}
We have also replaced Grid in place of Stack panel. But after adding grid, Text change event thrown "Object reference error"
The reason for the issue we have described is contained within the TextChanged event of the search TextBox we are using. A null reference exception is thrown because not all the items inside the ListBox are currently visualized, and this way the ContainerFromItem method is not able to find them all as visual elements. Since we have replaced the StackPanel with a Grid.