我正在尝试从 Linq 创建一个单一的选择列表框,但是,我在设置每个列表框项目的 ID 值时遇到了问题,该值具有保存在本地数据库中的相应 ID。我有以下代码:
public void display_Tips()
{
//commented out to try MrMDavidson's approach.
// listBoxTipHistory.Items.Clear();
// IList<Tips> tips = this.get_Tips();
// foreach (Tips tip in tips)
// {
// ListBoxItem li1 = new ListBoxItem();
// li1.Content = tip.date.Day + "-" + tip.date.Month + "-" +
// tip.date.Year + "-" + tip.date.Hour + ":" +
// tip.date.Minute + " - " + tip.resturant + " - $" +
// tip.tip_amount + " - $" + tip.billTotal;
// listBoxTipHistory.Items.Add(li1);
// }
if (listBoxTipHistory.Items.Count > 0)
{
listBoxTipHistory.Items.Clear();
}
listBoxTipHistory.ItemsSource = get_Tips();
}
public IList<Tips> get_Tips()
{
IList<Tips> tips = null;
using (TipContext context = new TipContext(conString))
{
IQueryable<Tips> query =
(from c in context.TipTable
orderby c.date descending
select c);
tips = query.ToList();
}
return tips;
}
本地数据库表:
[Table]
public class Tips
{
[Column(IsPrimaryKey = true, IsDbGenerated = true)]
public int tip_ID
{
get;
set;
}
[Column(CanBeNull = false)]
public float tip_amount
{
get;
set;
}
[Column]
public string resturant
{
get;
set;
}
[Column(CanBeNull = false)]
public DateTime date
{
get;
set;
}
}
Xaml 代码:
<ListBox SelectionChanged="showTipDetails" x:Name="listBoxTipHistory" Margin="6,3,0,0">
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding resturant}" />
<TextBlock Text="{Binding date}" />
<TextBlock Text="{Binding tip_amount}" />
</StackPanel>
</DataTemplate>
</ListBox >
我现在正在尝试重新编码以配合 MrMDavidson 的建议,但是,使用当前代码,它会导致列表显示“AppName.Tips”而不是实际的列数据。我已经尝试使用谷歌搜索演练和教程,但是,我一直无法提出解决方案。
此外,有没有特殊的方法来处理日期和时间?
如有任何建议,我们将不胜感激。
请您参考如下方法:
听起来您正在尝试通过 WinForms/CF.Net 风格的方法来执行此操作。虽然您可能可以这样做,但我建议您不要这样做,因为您实际上并没有获得 Silverlight 的值(value)。假设您的 Tips 类类似于;
public class Tip {
public int Id { get; set; }
public string Title { get; set; }
public string Restaurant { get; set; }
}
然后您可以将这些列表绑定(bind)到 ListBox;
listBoxTipHistory.ItemsSource = get_Tips()
您的 XAML 用于描述这些项目的显示方式;
<ListBox x:Name="listBoxTipHistory">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Title}" />
<TextBlock Text="{Binding Restaurant}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
ListBox 上的SelectedItem 将是当前选定的Tip(作为对象),而不是实际选择的 ListBoxItem。所以要得到选中的Tip的ID;
Tip selectedTip = listBoxTipHistory.SelectedItem as Tip;
if (selectedTip != null) {
Console.WriteLine("The selected Tip is {0}", selectedTip.Id);
}
进一步的建议是让您查看 INotifyPropertyChanged界面将允许对模型的更改自动在 UI 中更新
