Reputation: 156
What I am trying to make: I want to click on a button that lets me name my item. The item is then added to the listview.
So far the only way I can add an item is if I directly name it in the code. Here is my code so far:
private void button_add(object sender, RoutedEventArgs e)
{
ListViewItem item = new ListViewItem();
item.Content = "randommmmm";
list1.Items.Add(item);
}
Upvotes: 0
Views: 61
Reputation: 169320
Here is a very basic example that should give you the idea.
MainWindow.xaml.cs:
public partial class MainWindow: Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
popup.IsOpen = true;
}
private void txt_PreviewKeyDown(object sender, KeyEventArgs e)
{
if(e.Key == Key.Enter)
{
list1.Items.Add(txt.Text);
txt.Text = string.Empty;
popup.IsOpen = false;
}
}
}
MainWindow.xaml:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="Window6" Height="300" Width="300">
<StackPanel>
<ListView x:Name="list1" />
<Popup x:Name="popup" Width="300" PlacementTarget="{Binding ElementName=btn}">
<Border Background="White" BorderBrush="AliceBlue" BorderThickness="2">
<TextBox x:Name="txt" Margin="10" PreviewKeyDown="txt_PreviewKeyDown" />
</Border>
</Popup>
<Button x:Name="btn" Content="Add" Click="Button_Click" />
</StackPanel>
</Window>
Clicking on the Button
displays a Popup
with a TextBox
and when you press [Enter]
the text in the TextBox
is added to the ListView
.
If you are serious about WPF and XAML I really recommend you to learn the MVVM design pattern but that's another story :)
Upvotes: 1
Reputation: 546
You can bind a TextBox to a property in your view model.
<TextBox Text="{Binding ItemName}" />
private string itemName;
public string ItemName
{
get { return itemName; }
set
{
if (value == null || value == itemName) return;
itemName = value;
NotifyOnPropertyChanged(nameof(ItemName));
}
}
So you can use ItemName to create your item.
item.Content = ItemName;
Upvotes: 1