如何在XAML中将List作为ItemSource绑定到ListView? [英] How can I bind a List as ItemSource to ListView in XAML?
本文介绍了如何在XAML中将List作为ItemSource绑定到ListView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习WPF,并且希望有一个类似于LinkedList的集合,可以在其中添加和删除字符串.我希望有一个ListView
可以通过数据绑定来监听该集合.如何在XAML中将简单的列表集合绑定到ListView
?
I'm learning WPF and would like to have a collection similar to a LinkedList, to where I can add and remove strings. And I want to have a ListView
that listen to that collection with databinding. How can I do bind a simple list collection to a ListView
in XAML?
我的想法(不起作用)是这样的:
My idea (not working) is something like this:
<Window x:Class="TestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<LinkedList x:Key="myList"></LinkedList> //Wrong
<Window.Resources>
<Grid>
<ListView Height="100" HorizontalAlignment="Left" Margin="88,134,0,0"
Name="listView1" VerticalAlignment="Top" Width="120"
ItemsSource="{Binding Source={StaticResource myList}}"/> //Wrong
</Grid>
</Window>
我所有的代码(更新的版本,不起作用):
<Window x:Class="TestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Height="23" HorizontalAlignment="Left" Margin="12,12,0,0"
Name="textBox1" VerticalAlignment="Top" Width="120" />
<Button Content="Button" Height="23" HorizontalAlignment="Right"
Margin="0,12,290,0" Name="button1" VerticalAlignment="Top" Width="75"
Click="button1_Click" />
<ListView Height="100" HorizontalAlignment="Left" Margin="88,134,0,0"
Name="listView1" VerticalAlignment="Top" Width="120"
ItemsSource="{Binding myList}"/>
</Grid>
</Window>
C#代码:
namespace TestApp
{
public partial class MainWindow : Window
{
ObservableCollection<string> myList = new ObservableCollection<string>();
public MainWindow()
{
InitializeComponent();
myList.Add("first string");
}
private void button1_Click(object sender, RoutedEventArgs e)
{
myList.Add(textBox1.Text);
textBox1.Text = myList.Count+"st";
}
}
}
推荐答案
您只能将数据绑定到公共属性,并且需要设置DataContext.
You can only databind to public properties and you need to set the DataContext.
public partial class MainWindow : Window
{
public ObservableCollection<string> myList { get; private set; }
public MainWindow()
{
InitializeComponent();
myList = new ObservableCollection<string>();
myList.Add("first string");
DataContext = this;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
myList.Add(textBox1.Text);
textBox1.Text = myList.Count + "st";
}
}
这篇关于如何在XAML中将List作为ItemSource绑定到ListView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文