我创建了一个小的用户控件,其中包含一个 ICollectionView 和一个 ObservableCollection。
ObservableCollection<LogMessage> messages;
public ObservableCollection<LogMessage> Messages
{
get { return messages; }
}
ICollectionView log;
public ICollectionView Log
{
get { return log; }
}
变量在 UserControl 的构造函数中设置
public LogFilter()
{
messages = new ObservableCollection<LogMessage>();
log = new CollectionView(messages);
InitializeComponent();
#if DEBUG
messages.Add(new LogMessage("This is a general Message", MessageType.General));
messages.Add(new LogMessage("This is a server Message", MessageType.Server));
messages.Add(new LogMessage("This is an info", MessageType.Info));
messages.Add(new LogMessage("This is an error", MessageType.Error));
messages.Add(new LogMessage("This is a warning", MessageType.Warning));
#endif
}
UserControl 中的 ListView 绑定到 Log
<ListView x:Name="LogView" Grid.Row="0" ItemContainerStyle="{StaticResource LogMessageStyle}" ItemsSource="{Binding Log, ElementName=LogControl}" >
在 ListView 下方,有一个 Checkbox,它绑定了一个布尔值,指示是否应该过滤某一行。
<CheckBox IsChecked="{Binding HideServer, ElementName=LogControl}" VerticalAlignment="Center" Width="75">
public bool filterServer(object o)
{
LogMessage m = o as LogMessage;
if ((m.MessageType == MessageType.Server) && (hideServer == true))
return false;
return true;
}
public bool HideServer
{
get
{
return hideServer;
}
set
{
hideServer = value;
if (hideServer)
Log.Filter = new Predicate<object>(filterServer);
else
Log.Filter = null;
notifyPropertyChanged();
log.Refresh();
}
}
选中复选框后,过滤器会正确添加到 ICollectionView,但不会过滤列表框的内容。未调用 filterServer(object o) 函数。这段代码有问题吗?我用调试器单步执行了代码,看起来 Log.Refresh() 没有效果。
附加信息
PropertyChanged 事件定义为
public event PropertyChangedEventHandler PropertyChanged;
private void notifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
LogMessage 和 MessageType 定义为
public class LogMessage
{
public DateTime Timestamp { get; private set; }
public LogFilter.MessageType MessageType { get; private set; }
public string Message { get; private set; }
public LogMessage(string Message)
{
initalize(DateTime.Now, LogFilter.MessageType.General, Message);
}
public LogMessage(string Message, DateTime Timestamp)
{
initalize(Timestamp, LogFilter.MessageType.General, Message);
}
public LogMessage(string Message, LogFilter.MessageType MessageType)
{
initalize(DateTime.Now, MessageType, Message);
}
public LogMessage(string Message, DateTime Timestamp, LogFilter.MessageType MessageType)
{
initalize(Timestamp, MessageType, Message);
}
private void initalize(DateTime timestamp, LogFilter.MessageType messageType, string message)
{
Timestamp = timestamp;
MessageType = messageType;
Message = message;
}
}
public enum MessageType
{
Server,
Info,
Warning,
Error,
General
}