I have a JobItem object, and inside it, I have:
public ObservableCollection<string> BusinessUnit
{
get
{
return businessUnit;
}
set { businessUnit = value; }
}
Now the user needs to fill in a form and add in multiple Business Units. I have created a listbox that has add and delete buttons beside it. The add button opens a dialog that prompts the user to add the name of the business unit, then adds it to the list box. This is the code I have for this:
<my:ValidatingListBox Grid.Column="1" Grid.ColumnSpan="1" Grid.Row="5" Grid.RowSpan="1" x:Name="businessUnitBox" SelectionMode="Multiple" SelectionChanged="ValidatingListBox_SelectionChanged" IsSynchronizedWithCurrentItem="True">
<my:ValidatingListBox.ItemsSource>
<Binding Source="{StaticResource jobItemDataSource}" Path="BusinessUnit" Mode="TwoWay"/>
</my:ValidatingListBox.ItemsSource>
</my:ValidatingListBox>
<Button Style="{StaticResource addBtnStyle}" Grid.Column="2" Grid.Row="5" Name="addBusinessUnitBtn" Click="addBusinessUnitBtn_Click" />
<Button Style="{StaticResource removeBtnStyle}" Grid.Column="2" Grid.Row="5" Name="delBusinessUnitBtn" Click="delBusinessUnitBtn_Click" />
In the code behind, I’m binding the JobItem to the form because I have other textboxes that are bound to other JobItems (the binding works for this).
public NewJobDialog(int workOrderCounter)
{
InitializeComponent();
item = new JobItem();
base.DataContext = item();
businessUnitBox.DataContext = item.BusinessUnit;
}
Then when I click on the add button to add a business unit, I have this code:
private void addBusinessUnitBtn_Click(object sender, RoutedEventArgs e)
{
AddBusinessUnitDialog addBusinessUnit = new AddBusinessUnitDialog();
addBusinessUnit.ShowDialog();
if (addBusinessUnit.DialogResult == true)
{
item.BusinessUnit.Add(addBusinessUnit.BusinessUnit());
}
}
private void delBusinessUnitBtn_Click(object sender, RoutedEventArgs e)
{
if (businessUnitBox.Items.Count > 0)
{
item.BusinessUnit.Remove((string)businessUnitBox.SelectedItem);
}
}
Now when I run the program, every time I add a business unit, it does not show up in the listbox. Please give me some type of sample code as to how I would be able to get this to work. Thanks.
I believe it is because you need to set the DataContext to the parent class.
This is because you have the following binding
Additionally you can simplify the binding by having..
EDIT:
If you really want
Then your binding needs to be