【发布时间】:2014-11-02 08:42:56
【问题描述】:
我在用户控件中有以下元素,作为默认 Grid 的唯一子元素:
<ListView ItemsSource="{Binding LogCollection}" Name="LogView">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn DisplayMemberBinding="{Binding Level}" Header="Level"/>
<GridViewColumn DisplayMemberBinding="{Binding FormattedMessage}" Width="500" Header="Message"/>
<GridViewColumn DisplayMemberBinding="{Binding Exception}" Header="Exception"/>
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
在后面的代码中,我正在处理来自自定义 NLog Target 的以下事件。我只是因为给我一个例子而处理它,一个完全 WPF 菜鸟,但它似乎还可以。
private void EventReceived(LogEventInfo message)
{
Dispatcher.Invoke(() =>
{
if (LogCollection.Count >= 50)
{
LogCollection.RemoveAt(LogCollection.Count - 1);
}
LogCollection.Add(message);
});
}
事件触发良好,当我单步执行代码时,可以调用Add。当我在执行时将鼠标悬停在 XAML 视图中的 LogCollection 上时,我在 Addcall, yet myListView` 之后看到一个“Count = 1”,但我完全没有意识到它应该向我显示一个日志事件。
好的,好的,我的用户控件背后的删节代码是:
public partial class LoggingControl : UserControl
{
public ObservableCollection<LogEventInfo> LogCollection { get; set; }
public LoggingControl()
{
LogCollection = new ObservableCollection<LogEventInfo>();
InitializeComponent();
foreach (Target target in LogManager.Configuration.AllTargets)
{
var memoryEventTarget = target as MemoryEventTarget;
if (memoryEventTarget != null)
{
memoryEventTarget.EventReceived += EventReceived;
}
}
}
private void EventReceived(LogEventInfo message)
{
Dispatcher.BeginInvoke(new Action(() =>
{
LogCollection.Add(message);
}));
}
}
【问题讨论】:
-
双向绑定与此场景无关。
-
@MilanNankov 我同意,但还是给了它一个狂欢。我在必须绑定回集合的列表中没有做任何事情,它只能读取它。
-
顺便说一句,@MilanNankov 和我的 cmets 仅在另一个上下文中,因为已删除,建议 TwoWay 的评论。
-
LogCollection 可能是 ViewModel 上的一个属性?如果是这样,请确保该属性在您设置它时引发 PropertyChanged,因此每当您重新分配(或初始化)该属性时,绑定都会更新一个新的 Observable
实例。确保发布 ViewModel 的代码。 -
@ErnodeWeerd 不,
LogCollection是我声明ListView的控件的属性。我知道,我应该使用 ViewModel,但事情必须先正常工作才能正常工作。