我剛剛開始使用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