user688
user688

Reputation: 361

How to add a new item in listbox which binding from code behind to xaml page

ProjectInformation instance = lstbxindex.SelectedItem as ProjectInformation;
string name = instance.ProjectRow.Name;
IEditableCollectionView items = lstbxindex.Items;
if(items.CanRemove)
{
    items.Remove(lstbxindex.SelectedItem);
}

Using these lines of code remove listboxitems. after edit the values I need to add the values in listbox.

XAML

<ListBox ItemsSource="{Binding}" HorizontalContentAlignment="Left" x:Name="lstbxindex" SelectionMode="Extended" Foreground="White" FontSize="20px" Height="241" BorderBrush="#555555" Margin="10,34,16,0" VerticalAlignment="Top" Width="322" Background="#555555" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <WrapPanel Orientation="Horizontal" Margin="5" >
                <TextBlock Height="40px" Width="80px" Text="{Binding Roundedhour1}" FontSize="24" Background="#555555"  Foreground="Black"></TextBlock>
                <Label x:Name="items" Content="{Binding ProjectRow.Name}" Margin="35,0,0,0" MouseDoubleClick="items_MouseDoubleClick" Foreground="White"></Label>
            </WrapPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Upvotes: 0

Views: 1493

Answers (1)

mm8
mm8

Reputation: 169340

Set the ItemsSource property of the ListBox to an ObservableCollection<ProjectInformation> and add and remove items from this Collection using the Add and Remove methods.

XAML:

<ListBox HorizontalContentAlignment="Left" x:Name="lstbxindex" SelectionMode="Extended" Foreground="White" FontSize="20px" Height="241" BorderBrush="#555555" Margin="10,34,16,0" VerticalAlignment="Top" Width="322" Background="#555555" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <WrapPanel Orientation="Horizontal" Margin="5" >
                <TextBlock Height="40px" Width="80px" Text="{Binding Roundedhour1}" FontSize="24" Background="#555555"  Foreground="Black"></TextBlock>
                <Label x:Name="items" Content="{Binding ProjectRow.Name}" Margin="35,0,0,0" MouseDoubleClick="items_MouseDoubleClick" Foreground="White"></Label>
            </WrapPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Code:

public class ProjectInformation
{
    public int Roundedhour1 { get; set; }
}

public partial class MainWindow : Window
{
    private ObservableCollection<ProjectInformation> _sourceCollection = new ObservableCollection<ProjectInformation>();
    public MainWindow()
    {
        InitializeComponent();
        lstbxindex.ItemsSource = _sourceCollection;

        //add
        ProjectInformation item = new ProjectInformation() { Roundedhour1 = 1 };
        _sourceCollection.Add(item);
    }

    private void items_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        //remove
        _sourceCollection.Remove(lstbxindex.SelectedItem as ProjectInformation);
    }
}

Upvotes: 1

Related Questions