2013-03-08 77 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