user2483797
user2483797

Reputation: 169

wpf binding listbox item to a object

Can anyone help with the following, i've been around for a while a i cannot made it work. I want to save the data from a listbox wpf mvvm and add it to a list and to bind the listBox.

I've got a view model :

private const string StagePropertyName = "Stage";
        public string Stage
        {
            get
            {
                return _newProduct.Stage;
            }
            set
            {
                _newProduct.Stage = value;
                RaisePropertyChanged(StagePropertyName);
            }
        }

 public MainViewModel()
        {
            _newProduct = new Product();
            CreateAddCommand();

        }
private void CreateAddCommand()
        {
            AddCommand = new RelayCommand(AddExecute, CanExecuteAddCommand);
        }

        public void AddExecute()
        {
            Product.Add(_newProduct);
        }

And xaml:

 <ListBox Grid.Column="1" Grid.Row="2" Grid.RowSpan="2" Height="23" HorizontalAlignment="Left" Margin="20,5,0,0" Name="lstStage" VerticalAlignment="Top" Width="120" SelectedValuePath="Value" SelectedValue="{Binding Path=Stage, Mode=TwoWay}">
                <ListBoxItem>Item1</ListBoxItem>
                <ListBoxItem>Item2</ListBoxItem>
                <ListBoxItem>Item3</ListBoxItem>           
            </ListBox>        
            <Button Content="Add" Grid.Column="1" Grid.Row="6" Height="23" HorizontalAlignment="Left" Margin="25,10,0,0" Name="button1" VerticalAlignment="Top" Width="75" Command="{Binding Path=AddCommand}" />

public class Product
    {
        public string Name { get; set; }
        public string Deposit { get; set; }
        public string Lot { get; set; }
        public string Stage { get; set; }
        public string City { get; set; }

        public static void Add(Product product)
        {
            MessageBox.Show(product.Stage); //here is null

        }
    }

Trouble I am having is binding the SelectedItem/Value property of lstStage.

Please advice.

Upvotes: 0

Views: 557

Answers (1)

Chintan S
Chintan S

Reputation: 98

I am not quite sure if i understood your question. Do you want to access List-box's "selectedItem" when you click on Add button? If that's the requirement, one way to achieve it is to use command parameter as shown below.

<Button Content="Add" Grid.Column="1" Grid.Row="6" Height="23" HorizontalAlignment="Left" Margin="25,10,0,0" Name="button1" VerticalAlignment="Top" Width="75" Command="{Binding Path=AddCommand}" CommandParameter="{Binding ElementName=lstStage, Path=SelectedItem}"/>

you can then access selectedItem within your ICommand.Execute function as a parameter.

Upvotes: 2

Related Questions