In the following binding,
<TextBlock Text="{Binding Path=., StringFormat=TotalPages:{0}, Converter={StaticResource totalPagesConverter}}"/>
the totalPagesConverter
takes ObservableCollection<MyFileInfo>
and returns the total number of pages.
This works only for the first time, but doesn't not update when a MyFileInfo
object's property is changed. Note that I did implement INotifyPropertyChanged
for MyFileInfo
, and things update properly when they are binded to a Property of MyFileInfo
. But apparently something is missing when binding to a Collection
of such objects. How to bind to a Collection so that it updates properly? Thanks!
UPDATE Thank you all! properties of MyFileInfo
and the converter are shown below:
MyFileInfo
class
public class MyFileInfo : INotifyPropertyChanged
{
private Boolean ifPrint;
private Boolean isValid;
public string Filename {
get; set;
}
public string Filepath {
get; set;
}
public int Copies {
get; set;
}
public int Pages {
get; set;
}
public Boolean IfPrint {
get{
return this.ifPrint;
}
set{
if (this.ifPrint != value){
this.ifPrint = value;
onPropertyChanged("IfPrint");
}
}
}
public Boolean IsValid {
get {
return this.isValid;
}
set {
if (this.isValid!= value) {
this.isValid = value;
onPropertyChanged("IsValid");
}
}
}
private void onPropertyChanged(string propertyName) {
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Converter Class
public class TotalPagesConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
ObservableCollection<MyFileInfo> lst = (ObservableCollection<MyFileInfo>)value;
int t = 0;
foreach(MyFileInfo f in lst){
t += (f.IsValid && f.IfPrint) ? f.Pages : 0;
}
return t.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
}
A bit on the Converter: I have a CheckBox
for the user to choose files to be printed. Everytime the CheckBox
is toggled, the IfPrint
boolean property of an MyFileInfo
object is flipped. This Converter goes through all the IfPrint && IsValid
files to re-compute the total number of pages, and update the new total to-be-printed pages on GUI (ideally). This isn't that efficient, but the list is short (< 10). Any other idea is welcomed!