案例地址:GitHub - microsoft/WPF-Samples: Repository for WPF related samples
一、运行界面
二、案例功能描述
通过计时器控制属性值改变,属性值改变通知界面刷新
知识点:
1、INotifyPropertyChanged: 通知客户端属性值已更改。
但是也会受到绑定模式的影响。
三、分析代码
1、实现可通知属性值改变的类,继承INotifyPropertyChanged
public class Bid : INotifyPropertyChanged
{
private string _biditemname;
private decimal _biditemprice;
public Bid(string newBidItemName, decimal newBidItemPrice)
{
_biditemname = newBidItemName;
_biditemprice = newBidItemPrice;
}
public string BidItemName
{
get { return _biditemname; }
set
{
if (_biditemname.Equals(value) == false)
{
_biditemname = value;
// Call OnPropertyChanged whenever the property is updated
OnPropertyChanged("BidItemName");
}
}
}
public decimal BidItemPrice
{
get { return _biditemprice; }
set
{
if (_biditemprice.Equals(value) == false)
{
_biditemprice = value;
// Call OnPropertyChanged whenever the property is updated
OnPropertyChanged("BidItemPrice");
}
}
}
// Declare event
public event PropertyChangedEventHandler PropertyChanged;
// OnPropertyChanged to update property value in binding
private void OnPropertyChanged(string propName)
{
var handler = PropertyChanged;
handler?.Invoke(this, new PropertyChangedEventArgs(propName));
}
}
2、数据绑定
<DataTemplate x:Key="BidItemDataTemplate">
<Canvas Width="300" Height="20">
<TextBlock FontSize="14" Foreground="DarkSlateGray"
Width="180" Canvas.Left="0" Text="{Binding Path=BidItemName}"/>
<TextBlock FontSize="14" Foreground="DarkSlateBlue"
Text="$" Canvas.Left="180"/>
<TextBlock FontSize="14" Foreground="DarkSlateBlue"
Width="80" Canvas.Left="190" Text="{Binding Path=BidItemPrice}"/>
</Canvas>
</DataTemplate>
<ItemsControl Name="MyListBox" DockPanel.Dock="Top" Background="Silver"
Width="315" Height="80"
ItemsSource="{Binding Source={StaticResource MyDataSource}}"
ItemTemplate="{StaticResource BidItemDataTemplate}"/>