I am trying to write a simple application where I display a listview using databinding containing multiple objects that lists their properties and a check box. I let the user check all of the boxes they want removed then press a button that removes the selected elements.
public partial class MainWindow : Window
{
ObservableCollection<User> Users = new ObservableCollection<User>();
public MainWindow()
{
System.Console.WriteLine("main window");
Users.Add(new User() { Name = "John Doe", Age = 42, Height = "6ft", Checked = false});
Users.Add(new User() { Name = "Jane Doe", Age = 39, Height = "6ft", Checked = false });
Users.Add(new User() { Name = "Sammy Doe", Age = 7, Height = "5ft", Checked = false });
drawFolderView();
}
private void drawFolderView()
{
InitializeComponent();
lvUsers.ItemsSource = Users;
}
private void button_Click(object sender, RoutedEventArgs e)
{
if (Users.Count > 0)
{
List<User> itemsToRemove = new List<User>();
foreach (User person in Users)
{
if (person.Checked)
{
itemsToRemove.Add(person);
}
}
foreach (User person in itemsToRemove)
{
Users.Remove(person);
}
}
else
{
System.Console.WriteLine("nothing in list");
}
drawFolderView();
}
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
}
private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
{
}
}
public class User
{
public string Name { get; set; }
public int Age { get; set; }
public string Height { get; set; }
public bool Checked { get; set; }
public bool Equals(User other) {
if (Name.Equals(other.Name))
{
return true;
}
else
{
return false;
}
}
}
From reading the other questions I made the CheckBox_Checked and Unchecked methods, but I have no idea how to implement them.
Window x:Class="WpfApplication6.MainWindow"
xmlns="http://ift.tt/o66D3f"
xmlns:x="http://ift.tt/mPTqtT"
xmlns:d="http://ift.tt/pHvyf2"
xmlns:mc="http://ift.tt/pzd6Lm"
xmlns:local="clr-namespace:WpfApplication6"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListView Margin="10,10,10,98" Name="lvUsers">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
<GridViewColumn Header="Height" Width="150" DisplayMemberBinding="{Binding Height}" />
<GridViewColumn Width="60">
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox Margin="-4,0,-4,0" IsChecked="{Binding MyBoolProperty}" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked" DataContext="{Binding Checked}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
<Button x:Name="button" Content="Delete" HorizontalAlignment="Left" Margin="353,243,0,0" VerticalAlignment="Top" Width="75" Click="button_Click" />
</Grid>
Is this a reasonable approach? Many of the concepts surrounding databinding in WPF still confuse me.
Aucun commentaire:
Enregistrer un commentaire