开发者

wpf adding new items to a listbox

Sorry if the Syntax is off, i typed this on Notepad, (temp. issues with computer with VS)

i have a class Movie with a Title property, i have

 Dim movieList = New ObservableCollection(of Movie) 

 Private Sub SelectMovie(ByVal sender As Object, ByVal e As SelectionChangedEventArgs)

  For Each m As Movie in movieList
    If lb1.SelectedItem = "New" Then
      m.Add(New Movie()) 
    End If
   Next

 End Sub 

movieList was initialized with temp values, last one being "New".

In the constructor i iterated through movielist and put stuff in the listbox.

lb1.Items.Add(m)

开发者_如何转开发In the MainWindow.xaml i have

 <Grid Name="moviePage" > 
   <ListBox Name="lb1" SelectionChanged="SelectMovie">
 </Grid>

I'm aware that this approach is wrong as I'm modifying a list while using it, but i can't seem to find a way around this.

The idea is to simply have the listbox show a bunch of movies, with the ability to add a new movie if "New" is selected from the list.


Here's a working code sample:

public MainWindow()
{
    InitializeComponent();

    _movies = new ObservableCollection<Movie>(
        new[]
        {
            new Movie { Name = "Foo" },
            new Movie { Name = "Bar" },
            new Movie { Name = "(New)" },
        });
    lb1.ItemsSource = _movies;
}

ObservableCollection<Movie> _movies;

private void SelectMovie(object sender, SelectionChangedEventArgs e)
{
    var selectedMovie = lb1.SelectedItem as Movie;
    if (selectedMovie == null) return;

    if (selectedMovie.Name == "(New)")
    {
        var newMovie = new Movie { Name = "Untitled" };
        _movies.Insert(_movies.Count - 1, newMovie);
        lb1.SelectedItem = newMovie;
        e.Handled = true;
    }
}

Having said that, I don't believe this is the right approach for what you're doing. I think you're better off changing the template for the ListBox so that it shows the list of items it's bound to, and then a "New" button or link at the bottom (outside of the list).

Here's a very simple example:

<ListBox x:Name="lb1" DisplayMemberPath="Name" SelectionChanged="SelectMovie">
    <ListBox.Template>
        <ControlTemplate>
            <StackPanel>
                <ItemsPresenter />
                <Button Click="AddMovie>New Movie</Button>
            </StackPanel>
        </ControlTemplate>
    </ListBox.Template>
</ListBox>

So now you have a ListBox which includes a button to create a new movie. In your AddMovie event handler you can add a new Movie instance to the list and select it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜