[英]How to bind ListboxItem as observable collection in WPF and insert new record at the Top
我必須將我從后端收到的所有消息顯示到一個列表框中,例如
10:12:23 登錄成功。
10:13:00 注銷成功。
如何將此字符串消息綁定為列表項,並通過INotifyPropertyChange自動更新,條件是最近的項應插入第 0 個索引處。
我按照以下方式嘗試了此示例,這將對您有所幫助,
查看型號:
public VM()
{
items = new ObservableCollection<string>();
Items.Insert(0, "The time now is " + DateTime.Now.ToShortTimeString());
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(60) };
timer.Tick += (s, e) =>
{
Items.Insert(0,"The time now is " + DateTime.Now.ToShortTimeString());
};
timer.Start();
}
private ObservableCollection<string> items;
public ObservableCollection<string> Items
{
get { return items; }
}
將此項目綁定到 XAML 列表視圖
我很快就會把代碼分成幾部分; 你必須組裝它。
每個機構都使用 itemsource 到一個列表,在我的情況下它不起作用。
如果將列表的數據上下文設置為集合,則不能將其保留為有效的{Binding}
。 但是如果您的集合是視圖模型的一部分,那么您必須在綁定中指定集合名稱。
查看:
<ListBox ItemsSource="{Binding Logs}" />
<Button Click="AddLogEntry_Click" Content="Add log entry" />
視圖模型:
public class ViewModel1 : BaseViewModel
{
private ObservableCollection<string> logs;
public ObservableCollection<string> Logs {
get {
if (logs == null)
logs = new ObservableCollection<string>();
return logs;
}
}
// This is added for test
public void AddLogEntry() {
Logs.Insert(0, DateTime.Now.ToString());
}
}
查看代碼隱藏:
ViewModel1 vm;
public DisplayLatestItemInListbox() {
InitializeComponent();
vm = new ViewModel1();
DataContext = vm;
}
// Use command instead.
private void AddLogEntry_Click(object sender, RoutedEventArgs e) {
vm.AddLogEntry();
}
這里的關鍵是在ObservableCollection
上使用Insert
方法。 這就是你得到的:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.