This should be really easy, I just want to update the listview when the user adds something in the textbox to my observable collection.
I don’t understand why I can’t get this working:
XAML
<Window x:Class="MyStuff.WPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="486" Width="540" WindowStyle="SingleBorderWindow" ResizeMode="NoResize" >
<Grid>
<Menu IsMainMenu="True" VerticalAlignment="Top" HorizontalAlignment="Stretch" FlowDirection="LeftToRight">
<MenuItem Header="File" >
<MenuItem Header="Open File..">
</MenuItem>
<MenuItem Header="Exit">
</MenuItem>
</MenuItem>
</Menu>
<TextBox Height="36" HorizontalAlignment="Left" Margin="12,27,0,0" Name="textBoxSearchTerm" VerticalAlignment="Top" Width="414" FontSize="24" MaxLength="80" AcceptsReturn="False" Background="#FFFFFFE8" Text="asdfasdf" FontWeight="Bold" FontFamily="Calibri" FontStretch="Normal" />
<Button Content="Add" Height="36" HorizontalAlignment="Left" Margin="435,27,0,0" VerticalAlignment="Top" Width="68" FontSize="20" FontWeight="Normal" FontFamily="Calibri" Click="AddSearchTerm_Click" />
<ListView Height="338" HorizontalAlignment="Left" Margin="12,97,0,0" Name="listView1" VerticalAlignment="Top" Width="261" ItemsSource="{Binding SearchTerms}">
<ListView.View>
<GridView>
<GridViewColumn Width="120" Header="Search Term" DisplayMemberBinding="{Binding}" />
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
Code Behind
public partial class MainWindow : Window
{
public ObservableCollection<string> searchItems = new ObservableCollection<string>();
public MainWindow()
{
InitializeComponent();
}
// DEFINE A PROPERTY..
public ObservableCollection<string> SearchItems
{
get { return searchItems; }
}
private void AddSearchTerm_Click(object sender, RoutedEventArgs e)
{
searchItems.Add(textBoxSearchTerm.Text);
}
}
Tigrans answer is correct with regards to setting the datacontext. This is required to do databinding. There are a number of ways this can be accomplished but the easiest way would be to set the datacontext to your viewmodel (SearchItems).
Then your binding would look like
<ListView ... ItemSource={Binding}>Also you have
{Binding SearchTerm}a couple times but i do not see a property that it would be binding to (maybe a typo).Another option for binding the DataContext is to set it to the control itself:
This will change your binding expressions to
{Binding Path=SearchItems}as this will tell the binding engine to look for the SearchItems property on the current datacontext.Hope this helps.