2014-09-11 50 views
0

任何人都可以帮助以下,我已经围绕了一段时间,我不能使它的工作。 我想从列表框wpf mvvm保存数据并将其添加到列表并绑定列表框。wpf绑定列表框项目到一个对象

我有一个视图模型:

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); 
     } 

和XAML:我有约束力lstStage的的SelectedItem/Value属性

<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 

     } 
    } 

麻烦。

请指教。

+0

请显示属性/类'Product',其中暴露了'Add'方法来添加Product类的实例。也请显示属性'AddCommand' – pushpraj 2014-09-11 13:17:09

+0

更新代码请看看 – user2483797 2014-09-11 14:00:52

+1

尝试删除'SelectedValuePath =“Value”SelectedValue =“{Binding Path = Stage,Mode = TwoWay}”'并添加'SelectedItem =“{Binding Path = Stage,Mode = TwoWay}“'看看你是否仍然面临这个问题。 – pushpraj 2014-09-11 14:05:30

回答

2

我不太清楚,如果我理解你的问题。当你点击添加按钮时,你想访问列表框的“selectedItem”吗?如果这是要求,则实现它的一种方法是使用命令参数,如下所示。

<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}"/> 

然后,您可以访问ICommand.Execute函数中的selectedItem作为参数。