[英]How to add a new item in listbox which binding from code behind to xaml page
ProjectInformation instance = lstbxindex.SelectedItem as ProjectInformation;
string name = instance.ProjectRow.Name;
IEditableCollectionView items = lstbxindex.Items;
if(items.CanRemove)
{
items.Remove(lstbxindex.SelectedItem);
}
使用這些代碼行刪除listboxitems。 編輯值后,我需要在列表框中添加值。
XAML
<ListBox ItemsSource="{Binding}" HorizontalContentAlignment="Left" x:Name="lstbxindex" SelectionMode="Extended" Foreground="White" FontSize="20px" Height="241" BorderBrush="#555555" Margin="10,34,16,0" VerticalAlignment="Top" Width="322" Background="#555555" >
<ListBox.ItemTemplate>
<DataTemplate>
<WrapPanel Orientation="Horizontal" Margin="5" >
<TextBlock Height="40px" Width="80px" Text="{Binding Roundedhour1}" FontSize="24" Background="#555555" Foreground="Black"></TextBlock>
<Label x:Name="items" Content="{Binding ProjectRow.Name}" Margin="35,0,0,0" MouseDoubleClick="items_MouseDoubleClick" Foreground="White"></Label>
</WrapPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
將ListBox
的ItemsSource
屬性設置為ObservableCollection<ProjectInformation>
,然后使用Add
和Remove
方法從此Collection中添加和刪除項目。
XAML:
<ListBox HorizontalContentAlignment="Left" x:Name="lstbxindex" SelectionMode="Extended" Foreground="White" FontSize="20px" Height="241" BorderBrush="#555555" Margin="10,34,16,0" VerticalAlignment="Top" Width="322" Background="#555555" >
<ListBox.ItemTemplate>
<DataTemplate>
<WrapPanel Orientation="Horizontal" Margin="5" >
<TextBlock Height="40px" Width="80px" Text="{Binding Roundedhour1}" FontSize="24" Background="#555555" Foreground="Black"></TextBlock>
<Label x:Name="items" Content="{Binding ProjectRow.Name}" Margin="35,0,0,0" MouseDoubleClick="items_MouseDoubleClick" Foreground="White"></Label>
</WrapPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
碼:
public class ProjectInformation
{
public int Roundedhour1 { get; set; }
}
public partial class MainWindow : Window
{
private ObservableCollection<ProjectInformation> _sourceCollection = new ObservableCollection<ProjectInformation>();
public MainWindow()
{
InitializeComponent();
lstbxindex.ItemsSource = _sourceCollection;
//add
ProjectInformation item = new ProjectInformation() { Roundedhour1 = 1 };
_sourceCollection.Add(item);
}
private void items_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
//remove
_sourceCollection.Remove(lstbxindex.SelectedItem as ProjectInformation);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.