Home > Software engineering >  WPF - Can't add Listbox Item to Listbox (Beginner)
WPF - Can't add Listbox Item to Listbox (Beginner)

Time:05-20

When I try to add Listbox Item to my Listbox ( Properties -> Items -> [...] -> I choose ListBoxItem from the list -> Add ) and then instead of item being added to the list, I get "chosing object" popup where I need to "search for object", so I go: Presentation Framework -> System.Windows.Controls. -> ListBoxItem and then my form is crashing (System.NullReferenceException)

and then under that information I get huge list of things that I don't understand:

   w System.Object.GetType()
   w Microsoft.VisualStudio.DesignTools.Utility.Data.ShortToDoubleConverter.Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
   w System.Windows.Data.BindingExpression.TransferValue(Object newValue, Boolean isASubPropertyChange)
   w System.Windows.Data.BindingExpression.Activate(Object item)
   w System.Windows.Data.BindingExpression.AttachToContext(AttachAttempt attempt)
   w System.Windows.Data.BindingExpression.AttachOverride(DependencyObject target, DependencyProperty dp)
   w System.Windows.Data.BindingExpressionBase.OnAttach(DependencyObject d, DependencyProperty dp)
   w System.Windows.StyleHelper.GetInstanceValue(UncommonField`1 dataField, DependencyObject container, FrameworkElement feChild, FrameworkContentElement fceChild, Int32 childIndex, DependencyProperty dp, Int32 i, EffectiveValueEntry& entry)
   w System.Windows.FrameworkTemplate.ReceivePropertySet(Object targetObject, XamlMember member, Object value, DependencyObject templatedParent)
   w System.Windows.FrameworkTemplate.<>c__DisplayClass45_0.<LoadOptimizedTemplateContent>b__3(Object sender, XamlSetValueEventArgs setArgs)
   w System.Xaml.XamlObjectWriter.OnSetValue(Object eventSender, XamlMember member, Object value)
   w System.Xaml.XamlObjectWriter.Logic_ApplyPropertyValue(ObjectWriterContext ctx, XamlMember prop, Object value, Boolean onParent)
   w System.Xaml.XamlObjectWriter.Logic_DoAssignmentToParentProperty(ObjectWriterContext ctx)
   w System.Xaml.XamlObjectWriter.Logic_AssignProvidedValue(ObjectWriterContext ctx)
   w System.Xaml.XamlObjectWriter.WriteEndObject()
   w System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlReader templateReader, XamlObjectWriter currentWriter)
   w System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlObjectWriter objectWriter)
   w System.Windows.FrameworkTemplate.LoadOptimizedTemplateContent(DependencyObject container, IComponentConnector componentConnector, IStyleConnector styleConnector, List`1 affectedChildren, UncommonField`1 templatedNonFeChildrenField)
   w System.Windows.FrameworkTemplate.LoadContent(DependencyObject container, List`1 affectedChildren)
   w System.Windows.StyleHelper.ApplyTemplateContent(UncommonField`1 dataField, DependencyObject container, FrameworkElementFactory templateRoot, Int32 lastChildIndex, HybridDictionary childIndexFromChildID, FrameworkTemplate frameworkTemplate)
   w System.Windows.FrameworkTemplate.ApplyTemplateContent(UncommonField`1 templateDataField, FrameworkElement container)
   w System.Windows.FrameworkElement.ApplyTemplate()
   w System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   w System.Windows.UIElement.Measure(Size availableSize)
   w System.Windows.ContextLayoutManager.UpdateLayout()
   w System.Windows.ContextLayoutManager.UpdateLayoutCallback(Object arg)
   w System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
   w System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
   w System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
   w System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   w System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)

I tried to add ListBoxItem Manually in XAML, but then it gets underlined and VS says: "Operation is invalid when using Items.Source. Instead get acces to elements and change them with ItemsControl.ItemsSource properties.

The code:

 <Window x:Class="ExperimentWithControls.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:ExperimentWithControls"
            mc:Ignorable="d"
            Title="Eksperymenty z kontrolkami" Height="450" Width="800">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition/>
                <RowDefinition Height="0.5*"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Label Content="Wpisz liczbę" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="18" RenderTransformOrigin="-0.24,-0.246" Margin="10,10,0,0"/>
            <TextBlock x:Name="number" Grid.Column="1" HorizontalAlignment="Center" TextWrapping="Wrap" Text="Liczba" VerticalAlignment="Center" FontSize="24"/>
            <TextBox x:Name="numberTextBox" HorizontalAlignment="Left" Margin="10,44,0,0" TextWrapping="Wrap" Text="0" VerticalAlignment="Top" Width="120" FontSize="18" TextChanged="numberTextBox_TextChanged" PreviewTextInput="numberTextBox_PreviewTextInput"/>
            <ListBox Margin="10,10,10,10" Name="myListBox" HorizontalAlignment="Center" VerticalAlignment="Center" d:ItemsSource="{d:SampleData ItemCount=5}">
    
        </Grid>
    </Window>

Tried this manually:

<ListBox Margin="10,10,10,10" Name="myListBox" HorizontalAlignment="Center" VerticalAlignment="Center" d:ItemsSource="{d:SampleData ItemCount=5}">
<ListBoxItem Content="1"></ListBoxItem>
</ListBox>

But that does not work.

I've searched many posts but everyone has problems when accessing Listbox from C#, and I just want to create very basic form using WPF. Maybe I have not installed something but that's weird that I can add ListBox to the form but I can't add ListBox Item.

CodePudding user response:

Thank You guys,

I removed d:ItemsSource="{d:SampleData ItemCount=5} which was added automatically by the way and now I can add ListBox Items.

CodePudding user response:

You can try to drag and drop the listbox within the WPF form. And that uses the controls in the GUI to fill it.

This tutorial really helped me starting with listbox items: https://wpf-tutorial.com/list-controls/listbox-control/

  • Related