您好,登錄后才能下訂單哦!
在WPF應(yīng)用程序中,ListView
是一個(gè)常用的控件,用于展示一系列項(xiàng)目
以下是一個(gè)簡(jiǎn)單的自定義ListView
項(xiàng)模板實(shí)踐:
Person
的類,包含姓名、年齡等屬性。public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
ListView
定義一個(gè)ItemTemplate
。這個(gè)模板將決定每個(gè)列表項(xiàng)的外觀。<Window.Resources>
<DataTemplate x:Key="ListViewItemTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" Width="100" />
<TextBlock Text="{Binding Age, StringFormat='Age: {0}'}" Width="50" />
</StackPanel>
</DataTemplate>
</Window.Resources>
在這個(gè)模板中,我們使用了一個(gè)StackPanel
來(lái)布局兩個(gè)TextBlock
控件,分別顯示姓名和年齡。
3. 設(shè)置ListView的ItemTemplate:接下來(lái),在ListView
控件中設(shè)置ItemTemplate
屬性,引用我們剛剛創(chuàng)建的模板。
<ListView ItemsSource="{Binding People}">
<ListView.ItemTemplate>
<StaticResource ResourceKey="ListViewItemTemplate" />
</ListView.ItemTemplate>
</ListView>
這里,我們使用了StaticResource
來(lái)引用之前定義的模板。
4. 數(shù)據(jù)綁定:最后,確保你的MainWindow
類或其他數(shù)據(jù)上下文類中有一個(gè)名為People
的屬性,它包含了要顯示在ListView
中的數(shù)據(jù)。
public partial class MainWindow : Window
{
public ObservableCollection<Person> People { get; set; }
public MainWindow()
{
InitializeComponent();
People = new ObservableCollection<Person>
{
new Person { Name = "Alice", Age = 30 },
new Person { Name = "Bob", Age = 25 },
new Person { Name = "Charlie", Age = 35 }
};
}
}
現(xiàn)在,當(dāng)你運(yùn)行應(yīng)用程序時(shí),ListView
應(yīng)該會(huì)顯示每個(gè)項(xiàng)目的姓名和年齡,按照我們自定義的模板樣式。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。