【发布时间】:2014-07-23 22:32:29
【问题描述】:
向列表框添加新数据时,我在更新列表框时遇到了一些问题。这是我的代码
我的列表框有
<ListBox Name="EmailList" ItemsSource="{Binding ListBoxData, Mode=TwoWay}"
这是我的程序:
public partial class MainWindow : Window
{
string hostname = Properties.Settings.Default.pop_host;
int port = Properties.Settings.Default.pop_port;
bool useSsl = Properties.Settings.Default.pop_usessl;
string username = "recent:" + Properties.Settings.Default.username;
string password = Properties.Settings.Default.password;
// When this button is pressed the program starts a backgroundworker
// that begins the download of mails
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
BackgroundWorker getNewMail = new BackgroundWorker();
getNewMail.DoWork += newEmail;
getNewMail.RunWorkerAsync();
getNewMail.RunWorkerCompleted += updateList;
}
// The actual function that downloads the mails (Using OpenPOP)
private void newEmail(object sender, DoWorkEventArgs e)
{
List<Message> allEmail = FetchAllMessages(hostname, port, useSsl, username, password);
ListBoxData = new List<EmailEntry> { };
foreach (Message singleEmail in allEmail)
{
var mailData = new ListBoxDataClass { theMessage = singleEmail, truncate = 40 };
readyUpListBoxData(mailData);
ListBoxData.Add(new EmailEntry { from = mailData.displayName, subject = mailData.partOfBody, messageID = singleEmail.Headers.MessageId.ToString() });
}
}
public class ListBoxDataClass
{
public Message theMessage { get; set; }
public int truncate { get; set; }
public string partOfBody { get; set; }
public string displayName { get; set; }
}
// A function that does different things with the downloaded data
public void readyUpListBoxData(ListBoxDataClass data)
{
MessagePart theEmailTxt = data.theMessage.FindFirstPlainTextVersion();
string noLineBreaks = theEmailTxt.GetBodyAsText().ToString().Replace(System.Environment.NewLine, " ");
data.partOfBody = noLineBreaks.Length <= data.truncate ? noLineBreaks : noLineBreaks.Substring(0, data.truncate) + " ..";
data.displayName = data.theMessage.Headers.From.DisplayName.ToString();
if (data.displayName == "")
{
data.displayName = data.theMessage.Headers.From.Address.ToString();
}
data.displayName += " <" + data.theMessage.Headers.From.Address.ToString() + ">";
}
}
我相信我应该使用所谓的可观察集合或类似的东西?我只是看不到如何在我的程序中使用它。我希望你们中的一些人可以帮助我使用 Observable 集合或指出我可以使用的其他东西,这正是我需要的。
我正在考虑使用诸如计时器之类的东西来实现它,但我不确定这是否是一个好习惯?
【问题讨论】:
-
您将创建一个公共 observablecollection
ListBoxData 以便 xaml 可以访问它 -
尽管@Tsukasa 的推理很糟糕(xaml 可以访问它),但 是 正确答案。请查看 MSDN 上的ObservableCollection<T> Class 页面了解更多信息。
-
@Sheridan SO 应该给你警长批 :)
-
dude ...... 是 i>一个警长徽章,但它是一个金色的徽章,并且有一个人担任选举主持人至少1年 i> .反正我对这样的事情不感兴趣……我只是“看到就说”,所以如果有人添加了质量差的问题或答案,你最好相信我会告诉他们。 :)
标签: c# wpf data-binding listbox