|
此文章由 dalaohu 原创或转贴,不代表本站立场和观点,版权归 oursteps.com.au 和作者 dalaohu 所有!转贴必须注明作者、出处和本声明,并保持内容完整
ListBox binding datasource refresh 的問題。
簡化了的code如下。
Listbox
<ListBox Name="lbTimelog" Grid.Row="0">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding Start, Converter={StaticResource TimeFormatter}, Mode=TwoWay}" />
<TextBox Text="{Binding End, Converter={StaticResource TimeFormatter}, Mode=TwoWay}" />
<TextBox Text="{Binding Break, Mode=TwoWay}" />
<TextBlock Text="{Binding Total, Mode=TwoWay}" >
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Domain Model
public class Timelog : INotifyPropertyChanged
{
private DateTime _start;
public DateTime Start
{
get { return _start;}
set
{
_start = value;
RaisePropertyChanged("Start");
}
}
private DateTime _end;
public DateTime End
{
get { return _end; }
set
{
_end = value;
RaisePropertyChanged("End");
}
}
private double _break;
public double Break
{
get { return _break; }
set
{
_break = value;
RaisePropertyChanged("Break");
}
}
public double Total
{
get
{
return DateFormat.GetDiff(End, Start);
}
}
public event PropertyChangedEventHandler PropertyChanged;
void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Data Binding
lbTimelog.ItemsSource = log; //log = new ObservableCollection<Timelog>();
我想實現的功能是, 在UI上, 當用戶改了StartTime or EndTime, "Totoal" 應該自動刷新。 (Totoal 是個Computed property - value = End - Start)
在Xaml 的codebehind, 我有subscribe to datasource 的CollectionChanged event. 但這個event 只有當 new item added or removed from the collection 才trigger。 當你只是update existing item 時不會被trigger。
最後功能我是實現了。 通過 ReBound datasource. 就是每次我都 lbTimelog.ItemSource = log 一下。
但我認為這應該不是最好的方法, 理想中我是想功過TwoWay binding, 讓這個功能自動實現。
大家討論一下, 我silverlight也是新手, 還不太熟悉各項功能。。。 |
|