我有這個項目,我想弄清楚如何添加到列表視圖,然後能夠刪除它們。但我似乎不能得到itemsource綁定,除非我硬編碼。我如何在XAML中執行此操作?如何在WPF中正確設置我的itemsource以顯示我的ObservableCollection項目?
這增加了一個項目列表視圖
public partial class MainWindow : Window
{
private ObservableCollection<myItem> Item;
const string pattern = @"((.*)) (.*) left the game";
public MainWindow()
{
InitializeComponent();
}
private void btnAppend_Click(object sender, RoutedEventArgs e)
{
Item = new ObservableCollection<myItem>() { new myItem() { Username = "Prabhat" } };
lvUsers.ItemsSource = Item;
}
}
但是,如果刪除了硬編碼的ItemSource它不添加它,即使我想補充的ItemSource = {結合產品}到YM XAML
<Grid>
<ListView Name="lvUsers" ItemsSource="{Binding Item}" HorizontalAlignment="Left" Height="107" Margin="10,10,0,0" VerticalAlignment="Top" Width="497">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" Width="100" DisplayMemberBinding="{Binding Username}"/>
</GridView>
</ListView.View>
</ListView>
<TextBox Name="tbConent" HorizontalAlignment="Left" Height="78" Margin="10,122,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="497"/>
<Button Name="btnAppend" Click="btnAppend_Click" Content="Append" HorizontalAlignment="Left" Margin="213,220,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
編輯
類
public class myItem
{
public string Username { get; set; }
}
EDIT 2
MainWindow.xaml.cs
using System.Collections.ObjectModel;
using System.Windows;
namespace Listviewssssssssssssss
{
public partial class MainWindow : Window
{
public ObservableCollection<myItem> Item { get; private set; }
public MainWindow()
{
InitializeComponent();
}
private void btnAppend_Click(object sender, RoutedEventArgs e)
{
Item = new ObservableCollection<myItem>() { new myItem() { Username = "Prabhat" } };
lvUsers.Items.Refresh();
}
private void btnRemove_Click(object sender, RoutedEventArgs e)
{
}
}
}
可能的複製[C#從列表中填充列表視圖](https://stackoverflow.com/questions/45584249/c-sharp-populating-a-listview-from-a-list) – ASh
[MVVM](https://msdn.microsoft .com/en-us/library/hh848246.aspx)在使用WPF,特別是XAML Bindi ngs –