【问题标题】:wpf binding listbox item to a objectwpf 将列表框项绑定到对象
【发布时间】: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 等。

标签: wpf mvvm listbox


【解决方案1】:

我不太确定我是否理解您的问题。您想在单击添加按钮时访问列表框的“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 作为参数访问。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 2011-05-07
    • 1970-01-01
    相关资源
    最近更新 更多