Hi,
I want to create a 2 way bind between a listbox and a .NET list.
In my GUI, I have a listbox, a textbox and add and remove buttons.
The listbox displays cars, and my goal is to create a 2way bind between the .Net car list and the listbox: when the user enters a car into the textbox, it gets updated only in the .Net list, and the listbox is updated automatically.
When the user press the GUI "remove" button, a car gets removed from the GUI and the .Net list is updated automatically.
I've started to write the xaml code, but figured that I don't actually know how to do the binding on both sides (c# and xaml):
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:WpfApplication1"
Title="Window1" Height="300" Width="369" Loaded="Window_Loaded">
<Window.Resources>
<ObjectDataProvider x:Key="carsData"
ObjectType="{x:Type c:Window1}" />
</Window.Resources>
<Grid Width="332">
<ListBox Margin="10,62,0,100" Name="myListBox" HorizontalAlignment="Left" Width="120" ItemsSource="{Binding Source={StaticResource CarsData}}"/>
<Button Height="23" Margin="66,0,0,65" Name="addBtn" VerticalAlignment="Bottom" Click="addBtn_Click" HorizontalAlignment="Left" Width="64">add</Button>
<TextBox Margin="10,0,0,64.48" Name="myTextBox" Height="23" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="47" />
<Button Height="23" Margin="66,0,0,33" Name="removeButton" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="64" Click="removeButton_Click">Remove</Button>
</Grid>
</Window>
There is my c# code:
namespace WpfApplication1
{
public partial class Window1 : Window
{
MyModel listMgr;
ObservableCollection carList;
public Window1()
{
InitializeComponent();
listMgr = new MyModel();
}
private void addBtn_Click(object sender, RoutedEventArgs e)
{
listMgr.add(new Car(0, myTextBox.Text, 2011));
}
private void removeButton_Click(object sender, RoutedEventArgs e)
{
//myListBox.Items.RemoveAt(0);
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
carList = listMgr.getList();
myListBox.DataContext = carList;
//secondListBox.DataContext = carList;
}
}
}
Thanks, Li