Listbox and observablecollection in wpf



我有显示发票项目的listBox:

<ListBox x:Name="lbInvoice" ItemsSource="{Binding ocItemsinInvoice}"  Margin="10,27,0,143" Width="412" HorizontalAlignment="Left" BorderBrush="{x:Null}">
<ListBox.ItemTemplate>
<DataTemplate>
<ToggleButton x:Name="btnInvoiceItem" Checked="btnInvoiceItem_Checked" Style="{StaticResource InvoiceBG}" TabIndex="{Binding ItemsinInvoiceID}" Padding="20,0,0,0" FontSize="12" Width="408" Height="35" Foreground="#FFcfcfcf" IsChecked="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}, Mode=FindAncestor}}" BorderThickness="1,0.5">
<ToggleButton.BorderBrush>
<SolidColorBrush Color="#FF5B616F" Opacity="0.7"/>
</ToggleButton.BorderBrush>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Item.ItemName}" Width="200"/>
<TextBlock Text="{Binding SalePrice}" Width="50"/>
<TextBlock Text="{Binding Quantity,NotifyOnSourceUpdated=True}" Width="50"/>
<TextBlock Text="{Binding Total}" Width="50"/>
</StackPanel>
</ToggleButton>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

问题是当我更改代码后面的数量值时(例如点击事件)

ItemsinInvoice _lbi = (ItemsinInvoice)lbInvoice.SelectedItem;
_lbi.Quantity = 99; //for example

在屏幕上,列表中的数量值没有变化,我错过了什么。

感谢

如果您希望对ViewModel的更改自动反映在视图中,则您的类需要实现INotifyPropertyChanged,并且每次属性更改值时都需要引发PropertyChanged事件:

public class ItemsinInvoice : INotifyPropertyChanged
{
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
private int _quantity;
public int Quantity
{
get { return _quantity; }
set
{
if (_quantity != value)
{
_quantity = value;
OnPropertyChanged("Quantity");
}
}
}
}

更新

我不知道如何使用这个代码,你能解释一下吗?

这是一个非常简单的代码,但会尝试为您分解它。首先需要实现INotifyPropertyChanged接口

public class ItemsinInvoice : INotifyPropertyChanged

这个接口有一个PropertyChanged事件,您需要在类中发布它

public event PropertyChangedEventHandler PropertyChanged;

然后为指定的属性名称编写helper方法以安全地引发此事件:

private void OnPropertyChanged(string propertyName)
{
...
}

实现了CCD_ 5。现在,每次属性更改值时,您都需要用属性名称调用上面的OnPropertyChanged(...)方法,所以在本例中,对于public int Quantity { ... },您的调用看起来像这个OnPropertyChanged("Quantity"),您必须记住它区分大小写,因此属性名称必须完全匹配
通过实现INotifyPropertyChanged接口并为属性名称引发PropertyChanged事件,您可以告诉绑定具有此名称的属性已更改其值,并且所有相关绑定都需要刷新。

最新更新