Skip to main content
 首页 » 编程设计

c#之使用 List> 时使用 ListBox(带有 ItemTemplate)的正确方法

2024年02月20日13lori

我一直在尝试使用我在 ListBox 中的 Model.Person 的 List<>,使用 ItemTemplate 作为样式,然后在选择一个时从列表中检索正确的 Model.Person。我到处寻找示例代码(并尝试了领先的数据绑定(bind),但仍然无法正确理解它)。

List<Model.Person> people = (comes from IsolatedStorageSettings) 

在一个页面上我有一个列表框,假设名为“列表”。

<ListBox Name="List"></ListBox> 

在我的 C# 代码中,我从独立存储中提取了一个列表。我最理想的做法是让该列表中的所有人以格式良好的方式出现在 ListBox 中,然后在选择一个人时,轻松地从 List<> 中检索 Person。 我现在正在做的事情肯定是错误的:

foreach (Model.Person person in people) 
{ 
    List.Items.Add(person.firstName + " " + person.lastName); 
} 

然后,当一个项目被选中时,我找到使用这个方法的人:

string selectedPerson = List.SelectedItem.ToString(); 
Model.Person person = people.Where(X => X.firstName + " " + X.lastName == selectedPerson).FirstOrDefault(); 

显然,项目中的列表仅显示为纯文本,而不是使用 ItemTemplate 创建的有趣对象。有人可以告诉我我做错了什么或指出实现此目标的良好资源方向吗?

非常感谢!

请您参考如下方法:

你真的想在 View 中做与 View 相关的事情,而不是在后面的代码中。因此,不要用代码手动填充列表,而是将其绑定(bind)到 View 中。 XAML 可能看起来像这样:

<ListBox ItemsSource="{Binding Path=People}" SelectedItem="{Binding Path=SelectedPerson, Mode=TwoWay}"> 
    <ListBox.ItemTemplate> 
        <DataTemplate> 
            <StackPanel Orientation="Horizontal"> 
                <TextBlock Text="{Binding Path=FirstName}" /> 
                <TextBlock Text="{Binding Path=LastName}" /> 
            </StackPanel> 
        </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

为您的页面使用结构清晰的 ViewModel,其中包含一个成员 People 和一个用于选定的 Person。它看起来像:

public class YourPageViewModel : INotifyPropertyChanged 
{ 
    public List<Model.Person> People { get; set; } 
 
    private Model.Person _selectedPerson; 
    public Model.Person SelectedPerson 
    { 
        get 
        { 
            return _selectedPerson; 
        } 
        set 
        { 
            if (_selectedPerson != value) 
            { 
                _selectedPerson = value; 
                PropertyChangedEventHandler handler = this.PropertyChanged; 
                if (handler != null) 
                    handler(this, new PropertyChangedEventArgs(propertyName)); 
            } 
        } 
    } 
} 

然后在view的代码后面设置viewmodel:

public partial class MainPage : PhoneApplicationPage 
{ 
    public MainPage() 
    { 
        InitializeComponent(); 
 
        this.Loaded += (s, e) => 
        { 
            if (DataContext == null) 
                DataContext = new YourPageViewModel(); 
        }; 
    } 
} 

瞧,您正在使用 MVVM 方法,而不是从后面的代码填充 View 。

此外,我建议不要滥用 IsolatedStorageSettings 来存储应用程序的实际数据。为你的模型对象使用序列化器,或者使用 SQL compact Windows Phone 的数据库来执行此操作。