【发布时间】:2014-11-05 08:19:43
【问题描述】:
任何人都可以帮助解决以下问题,我已经有一段时间了,我无法让它工作。 我想从列表框 wpf mvvm 中保存数据并将其添加到列表中并绑定列表框。
我有一个视图模型:
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:
<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
}
}
我遇到的问题是绑定 lstStage 的 SelectedItem/Value 属性。
请指教。
【问题讨论】:
-
请显示属性/类
Product,它公开Add方法以添加产品类的实例。也请出示房产AddCommand -
更新代码请看
-
尝试删除
SelectedValuePath="Value" SelectedValue="{Binding Path=Stage, Mode=TwoWay}"并添加SelectedItem="{Binding Path=Stage, Mode=TwoWay}",看看您是否仍然遇到问题。 -
问题解决了一半。你知道为什么舞台被保存为: System.Windows.Controls.ListBoxItem: Item1 吗?非常感谢。
-
添加到 ListBox 的任何项目都包装在 ListBoxItem 中,同样,ComboBoxItem 用于 ComboBox,ListViewItem 用于 ListView。所以它只是一个包装器来托管项目并提供容器特定的功能,例如。 ListBoxItem 提供 IsSelected 等。