2013-03-08 72 views
-3

我刚刚开始使用WPF,并开始使用,我想知道如何以编程方式将具有'Name'属性的自定义类的实例添加到列表框,并且列表框将在UI中显示每个元素作为其名称,而不是“MyNamespace.CustomClass”。WPF数据绑定的基础知识

我已经阅读了有关DataContexts和DataBinding和DataTemplates的模糊内容,但我想知道我可以做的绝对最小值,最好是尽可能使用尽可能小的XAML - 我觉得它非常令人迷惑。

谢谢!

+0

XAML没有真正的解决方法。你需要处理它。而且它也使一些事情变得非常简单! [MSDN](http://msdn.microsoft.com/zh-cn/library/aa970268.aspx)上有足够的教程。 – 2013-03-08 14:23:44

+1

DataContexts和DataBinding是WPF的绝对最小值 – Kcvin 2013-03-08 14:24:36

+0

看起来每个教程都使用了大量的XAML,并且该主题的相关章节从未明确过。但是,我知道我需要能够处理一些问题。 – Miguel 2013-03-08 14:25:31

回答

3

我知道你想避免绑定,但我会抛出这个无论如何。尽量不要太害怕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上面的代码应该显示这一点。 enter image description here

+0

好吧你已经说服我尝试了,我基本上复制了你的代码,改变了相关的数据类型和属性名称,然而列表视图却没有显示任何东西 - 即使调试器显示'Items'集合已被填充也没有。 – Miguel 2013-03-09 07:58:44

+0

我只是试图在代码中复制一个新项目,将结果粘贴为图像,似乎工作正常 – Andy 2013-03-09 11:53:48

+0

啊是的,这是我的错 - 我没有'理解语法,所以我以某种方式在第一个列表框中定义了第二个列表框......但是,感谢您提供了这个简单的解释,这正是我需要的! – Miguel 2013-03-09 13:20:10