我尝试将单例绑定到listview。 单例是一个简单的日志记录类,它将所有新的传入日志记录消息放在一个可观察对象中。该对象绑定到我的xaml代码。
单身人士课程:
namespace Log
{
public sealed class CLog
{
private CLog() { }
private static object m_lock = new object();
private static CLog _instance;
public static CLog instance
{
get
{
if (_instance == null)
{
lock (m_lock)
{
if (_instance == null)
{
_instance = new CLog();
}
}
}
return _instance;
}
}
private ObservableCollection<CLogMessage> _logs = new ObservableCollection<CLogMessage>();
public ObservableCollection<CLogMessage> logs
{
get
{
if (_logs == null)
{
_logs = new ObservableCollection<CLogMessage>();
}
return _logs;
}
}
public void AddString(string source, string message)
{
CLogMessage log = new CLogMessage();
log.time = DateTime.Now;
log.source = source;
log.message = message;
System.Windows.Application.Current.Dispatcher.Invoke(
(Action)delegate()
{
logs.Add(log);
});
}
}
public sealed class CLogMessage
{
public DateTime time { get; set; }
public string source { get; set; }
public string message { get; set; }
}
}
我在ListView中的绑定:
<Grid>
<ListView ItemsSource="{Binding Source={x:Static local:CLog.instance}, Path=logs}">
<ListView.View>
<GridView>
<GridViewColumn Header="Zeit" Width="140" DisplayMemberBinding="{Binding time}"/>
<GridViewColumn Header="Quelle" Width="140" DisplayMemberBinding="{Binding source}"/>
<GridViewColumn Header="Nachricht" Width="Auto" DisplayMemberBinding="{Binding message}"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
问题是我的视图没有更新。我通过来自不同类的简单CLog.instance.logs.Count()随机测试了单例类的调试目的。绝对精细,我只是在我的视图中显示项目时遇到问题。 我非常模糊的建议是我必须为绑定对象本身实现通知吗?
谢谢
答案 0 :(得分:0)
我认为问题是由于listview从一开始就被绑定到null项源。由于我现在没有机器来测试,也许您可以通过更改_logs
周围的代码来验证是否属实:
private ObservableCollection<CLogMessage> _logs =
new ObservableCollection<CLogMessage>();
public ObservableCollection<CLogMessage> logs
{
get { return _logs; }
}
public void AddString(string source, string message)
{
CLogMessage log = new CLogMessage();
log.time = DateTime.Now;
log.source = source;
log.message = message;
System.Windows.Application.Current.Dispatcher.Invoke(
(Action)delegate()
{
_logs.Add(log);
});
}