我刚刚开始使用WPF,并开始使用,我想知道如何以编程方式将具有'Name'属性的自定义类的实例添加到列表框,并且列表框将在UI中显示每个元素作为其名称,而不是“MyNamespace.CustomClass”。WPF数据绑定的基础知识
我已经阅读了有关DataContexts和DataBinding和DataTemplates的模糊内容,但我想知道我可以做的绝对最小值,最好是尽可能使用尽可能小的XAML - 我觉得它非常令人迷惑。
谢谢!
我刚刚开始使用WPF,并开始使用,我想知道如何以编程方式将具有'Name'属性的自定义类的实例添加到列表框,并且列表框将在UI中显示每个元素作为其名称,而不是“MyNamespace.CustomClass”。WPF数据绑定的基础知识
我已经阅读了有关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>
在窗口的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上面的代码应该显示这一点。
XAML没有真正的解决方法。你需要处理它。而且它也使一些事情变得非常简单! [MSDN](http://msdn.microsoft.com/zh-cn/library/aa970268.aspx)上有足够的教程。 – 2013-03-08 14:23:44
DataContexts和DataBinding是WPF的绝对最小值 – Kcvin 2013-03-08 14:24:36
看起来每个教程都使用了大量的XAML,并且该主题的相关章节从未明确过。但是,我知道我需要能够处理一些问题。 – Miguel 2013-03-08 14:25:31