Adil
Adil

Reputation: 3

How do I loop through a multi-column listbox in WPF?

I am a beginner with WPF. I fear this may sound like a silly question.

I have a listbox with two columns. Each listbox item contains a horizontal stacked panel which in turn contains textblocks.

The listbox is empty, with each listbox item being added by the end-user through a couple of textboxes placed elsewhere. The first column accepts strings, and the second column accepts only percentages.

(I have attached a relevant portion of the event sub where a user is adding new rows.)

Private Sub btnAddItem_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles btnAddSplit.Click

'...

Dim ListBoxItemName As New TextBlock
ListBoxItemName.Text = Name.Text
ListBoxItemName.Width = 170

Dim ListBoxItemValue As New TextBlock
ListBoxItemValue.Text = SplitValue.Text
ListBoxItemValue.Width = 70

Dim ListBoxStackPanel As New StackPanel
ListBoxStackPanel.Orientation = Orientation.Horizontal
ListBoxStackPanel.Children.Add(ListBoxItemName)
ListBoxStackPanel.Children.Add(ListBoxItemValue)

Dim NewEntry As New ListBoxItem
NewEntry.Content = ListBoxStackPanel

MyListBox.Items.Add(NewEntry)

'...

End Sub 

I would like to be able to check every time the above event is fired that the column of percentages does not exceed 100%. I have a couple of labels below the listbox itself where I would like to show the running total and the remainder.

My questions are:

1) How can I loop through the second column of percentages to show the running total and remainder?

2) Is there something more suitable than a ListBox that could make this easier?

I would appreciate any sort of guidance towards a solution on this, regardless of whether it is in VB or C#. Thank you very much.

Upvotes: 0

Views: 705

Answers (2)

drowned
drowned

Reputation: 550

Based on your code sample, it appears as if you're going through the same issues I went through when I first started with WPF. It's difficult to let go of that codebehind mentality and to embrace databinding, but I think you should give it a try. You will probably find that it's worth it.

Ultimately, I think your best bet would be to bind some collection of objects to the listbox and then iterate through this collection, like...

<ListBox ItemsSource="{Binding StringPercentageCollection}" ... /> And bind your columns, or your textblocks, or whatever your layout is, to the public properties of "YourStringPercentageObject".

And then "StringPercentageCollection" might be an ObservableCollection (or some other collection) of YourStringPercentageObject in the data context. Then you'd be able to iterate through the observable collection normally.

Upvotes: 1

Jesse Seger
Jesse Seger

Reputation: 960

I would keep track of the percentage in another field if possible. This would separate your implementation from your user interface which is generally a good idea.

Upvotes: 0

Related Questions