我刚刚开始使用 WPF,首先,我想知道如何以编程方式将我自己的自定义类的实例添加到列表框中,并且列表框将每个元素显示为它在 UI 中的名称,而不是“MyNamespace.CustomClass”。
我已经阅读了有关 DataContexts 和 DataBinding 和 DataTemplates 的模糊内容,但我想知道我能做的绝对最低限度,最好使用尽可能少的 XAML - 我觉得它相当令人困惑。
谢谢!
我刚刚开始使用 WPF,首先,我想知道如何以编程方式将我自己的自定义类的实例添加到列表框中,并且列表框将每个元素显示为它在 UI 中的名称,而不是“MyNamespace.CustomClass”。
我已经阅读了有关 DataContexts 和 DataBinding 和 DataTemplates 的模糊内容,但我想知道我能做的绝对最低限度,最好使用尽可能少的 XAML - 我觉得它相当令人困惑。
谢谢!
我知道你想避免绑定,但无论如何我都会把它扔掉。尽量不要太害怕 XAML,刚开始有点疯狂,但是一旦你习惯了所有的 {binding},它实际上很明显,一个简单的例子将列表框绑定到后面的代码中的集合就可以了像这样。
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="MainWindow" Height="350" Width="525">
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Window>
Window 中的 DataContext 属性告诉它默认绑定的位置(在本例中是窗口),数据模板告诉列表框如何显示集合中找到的每个项目。
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
public class MyClass
{
public string Name { get; set; }
}
public partial class MainWindow : Window
{
public ObservableCollection<MyClass> Items
{
get { return (ObservableCollection<MyClass>)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
public static readonly DependencyProperty ItemsProperty =
DependencyProperty.Register("Items", typeof(ObservableCollection<MyClass>), typeof(MainWindow), new PropertyMetadata(null));
public MainWindow()
{
InitializeComponent();
Items = new ObservableCollection<MyClass>();
Items.Add(new MyClass() { Name = "Item1" });
Items.Add(new MyClass() { Name = "Item2" });
Items.Add(new MyClass() { Name = "Item3" });
Items.Add(new MyClass() { Name = "Item4" });
Items.Add(new MyClass() { Name = "Item5" });
}
}
}
当粘贴到 Visual Studio 中时,上面的代码应该会显示这一点。