Databinding 2 WPF ComboBoxes to 1 source without being "linked" - wpf

I have a master-detail scenario where I have 1 ComboBox listing companies from an ObjectDataSourceProvider. Under that I have 2 ComboBoxes binding to the Contacts property from the current Company object. I need to be able to select a different contact in each ComboBox; however, as soon as I change selection in one list the other list updates to the same contact.
I have tried different settings (OneWay vs. TwoWay) but so far nothing seems to work. Here is an excerpt of my XAML.
<Page.Resources>
<!-- This is a custom class inheriting from ObjectDataProvider -->
<wg:CustomersDataProvider x:Key="CompanyDataList" />
</Page.Resources>
<Grid>
<!--- other layout XAML removed -->
<ComboBox x:Name="Customer" Width="150"
ItemsSource="{Binding Source={StaticResource CompanyDataList},Path=Companies,Mode=OneWay}"
DisplayMemberPath="Name"
SelectedValuePath="Id"
IsSynchronizedWithCurrentItem="True"
SelectedValue="{Binding Path=Id, Mode=OneWay}"
VerticalAlignment="Bottom" />
<ComboBox x:Name="PrimaryContact" Width="150"
DataContext="{Binding ElementName=Customer,Path=Items,Mode=OneWay}"
ItemsSource="{Binding Path=Contacts,Mode=OneWay}"
DisplayMemberPath="FullName"
SelectedValuePath="Id"
IsSynchronizedWithCurrentItem="True"
SelectedValue="{Binding Path=Id,Mode=OneWay}" />
<ComboBox x:Name="AdminContact" Width="150"
DataContext="{Binding ElementName=OwnerCustomer,Path=Items,Mode=OneWay}"
ItemsSource="{Binding Path=Contacts,Mode=OneWay}"
DisplayMemberPath="FullName"
SelectedValuePath="Id"
IsSynchronizedWithCurrentItem="True"
SelectedValue="{Binding Path=Id,Mode=OneWay}" />
<!--- other layout XAML removed -->
</Grid>
I thought that creating a CollectionViewSource would be the way to go, but I have not been able to make that work. Is there a simple way to do this so the PrimaryContact and AdminContact aren't linked?

Change your "IsSynchronizedWithCurrentItem" attributes to "False".

Related

WPF DataGrid RowDetailsTemplate with Multiple Images (MVVM)

Goal
To add multiple images in a DataGrid's RowDetails template using the MVVM standards.
Background
I have an inspection window with a DataGrid designed to hold a damaged item's description along with the initials of the inspector. What is more, this DataGrid's RowDetailsTemplate needs to hold the pictures that the inspector took of the damaged item (so there might be more than one picture of the damaged item).
Problem
I have a DamagedWindow.xaml designed to create my DamagedItem entries. It looks like this:
DataGrid (.XAML)
<DataGrid ItemsSource="{Binding Pictures}" SelectedItem="{Binding SelectedPicture}" AutoGenerateColumns="False" Grid.Column="1" Grid.Row="2" Margin="5" HorizontalAlignment="Stretch" Name="DataGrid1" VerticalAlignment="Stretch" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Titre" Binding="{Binding Name}" Width="*" />
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<Image Height="100" Source="{Binding Path}" />
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
As you can see, my RowDetails template works fine in this DataGrid. I have a class named PicturesList which inherits an ObservableCollection Of my PictureModel(Name, Description, Path).
The text boxes that you see above the DataGrid are properties of my DamagedItemModel (Description, Initiales, PicturesList). So when the user clicks on the Accept (Checkmark) button, the DamagedItem is added to a DamagedItemsList which is then set as the ItemSource of the DataGrid from my MainWindow:
DataGrid (.XAML)
<DataGrid ItemsSource="{Binding Path=DamagedItems}" SelectedItem="{Binding Path=SelectedDamagedItem}" AutoGenerateColumns="False" Name="DataGrid1" Height="250" Margin="3" IsEnabled="True" CanUserAddRows="False" FontSize="16">
<DataGrid.Columns>
<DataGridTextColumn Header="Description" Width="*" Binding="{Binding Description}"/>
<DataGridTextColumn Header="Initiales" Width="70" Binding="{Binding Initiales}"/>
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<Image Height="100" Source="{Binding Pictures.Path}" />
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
Here when I select the row, I get an empty RowDetailsTemplate result ... Even though my object contains my images. See below for more details:
So here's my question, is it possible to add multiple images to a RowDetailsTemplate in a DataGrid while following MVVM standards? If it is, what am I doing wrong?
You can't bind that way. you need to do it like this:
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding Pictures}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Height="100" Source="{Binding Path}"/>
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
The reason your method was not working is that the Binding source is always one object which is set by Binding Path, and your Binding Path was Pictures.Path which leads to nothing because Pictures object does not have Path, it's its Items which have Path.
In general, Whenever you find yourself dealing with a collection of some kind think of a control which is suitable for showing a collection, like ListBox, DataGrid or the best of all ItemsControl.
Anything that goes inside ItemTemplate of these controls, have their DataContext automatically set to the correspondent item, so you don't have to worry about it. All you have to do is to set the ItemsSource to your collection and set the Binding Paths of things inside to the properties of the Type of that collection, So that it knows where to look for data for each item.
In this code you can think of it this way, Like you have some StackPanels, first one has : Image Source="{Binding Pictures(0).Path}", seconds one has Image Source="{Binding Pictures(1).Path}" and so on. this way all Binding Paths point to an object.

Nested Datagrid in ListBox

I have a datagrid nested inside the ItemTemplate of a ListBox. I'm trying to display a tree like data structure using this. My classes are as follows.
The object in my data context contains a List<Section> named Sections, my ListBox is bound to this. Each Section contains a List<Item> named Items, the DataGrid in eac ItemTemplate is bound to this.
When I run the app, I get a null reference exception from the XAML at the line with the binding. Is there a better/alternative way of doing this, or am I missing a trick with the binding?
<Window.Resources>
<CollectionViewSource x:Key="SectionSource" /><!-- this is initialized and filled with an ObservableCollection<Section> Sections when the window loads-->
</Window.Resources>
<ListBox x:Name="lstIngredients" ItemsSource="{Binding Source={StaticResource SectionSource}}">
<ListBox.ItemTemplate>
<DataTemplate>
<DataTemplate.Resources>
<CollectionViewSource x:Key="itemsSource" Source="{Binding Items}"/>
</DataTemplate.Resources>
<DataGrid x:Name="dgItems" IsReadOnly="false" AutoGenerateColumns="False" SelectionMode="Single" SelectionUnit="FullRow" IsSynchronizedWithCurrentItem="True"
DataContext="{Binding}"
ItemsSource="{Binding Source={StaticResource Items}}"
EnableRowVirtualization="false"
VirtualizingStackPanel.VirtualizationMode="Standard"
<DataGrid.Columns>
<DataGridTemplateColumn Width="2*" Header="{lex:LocText ChickenPing.Shared:Strings:Measurement}">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock x:Name="quantity" Text="{Binding Measurement}" TextTrimming="CharacterEllipsis" TextAlignment="Left"/>
<!-- Null reference on this line caused by the binding. If I set this to any DependencyProperty on an Item object, I get a null reference-->
</DataTemplate>
This need to be path
ItemsSource="{Binding Source={StaticResource Items}}"
ItemsSource="{Binding Path=PropertyThatIsCollection}"
And delete the DataContext line
I eventually tracked this down to an event which was set in one of the TemplateColumns. Switching the event from
<TextBlock x:Name="quantity" Text="{Binding Measurement}" GotFocus="txt_GotFocus" />
to
<Style x:Key="FocusableTextbox" TargetType="{x:Type TextBox}">
<EventSetter Event="GotFocus" Handler="txt_GotFocus" />
</Style>
...
<TextBlock x:Name="quantity" Text="{Binding Measurement}" Style={StaticResource FocusableTextbox} />

How do I bind to different property on ComboBox SelectedItem?

I have a combobox in WPF like this:
<ComboBox Text="Select Language..." IsEditable="True" IsReadOnly="True"
ItemsSource="{Binding XPath=item/#name, Source={StaticResource Items}}"
SelectedItem="{Binding Path=Test, Mode=OneWayToSource}"/>
Where Items is:
<XmlDataProvider x:Key="Items" Source="/itemlist.xml" XPath="/itemlist"/>
Test is a property of type object on ViewModel that is set as datacontext of a window.
Everything works fine, and my Test property receives XmlNode object, which makes sense.
However, I would like to receive different attribute from that xml for example XPath=item/#value
How do I do that?
Use DisplayMemberPath and SelectedValuePath:
<ComboBox Text="Select Language..." IsEditable="True" IsReadOnly="True"
ItemsSource="{Binding XPath=item, Source={StaticResource Items}}"
DisplayMemberPath="#name"
SelectedValuePath="#id"
SelectedValue="{Binding Path=Test, Mode=OneWayToSource}"/>
The selected item will be the item element, it will display the name attribute, and it will bind the id attribute to Test.

Accessing control between DataGridCells, dynamic cascading ComboBoxes

I have a DataGrid that two of its columns are ComboBoxes (one contains few but not this is the problem).
I want, that when the user changes the first Combo's value, the ComboBox in the other column should bind to a property of its (this property is a collection). Say the First ComboBox is Category, I want that when the user changes its value, the other CB is populated with the values of (first combo's selected category).Vendors.
How should I do it, I don't use MVVM, just simple WPF.
I don't know what should be the right way to implement it, I hope I started it right.
I think, if I could get the other ComboBox (which is located in a different DataGridCell) from the first's SelectionChangeHandler that would be the best, because then I can reset its source on each selection change of the first one.
Note that I have the capability of reaching the current (the first's) DataGridCell, I am just looking for an efficient way to access the right DataGridCell sibling and then get its child (second) combo.
Also note that the selected category should vary from row to row, and the second ComboBox should depend on this row's category.
I actually tried to implement it so that the CollectionViewSource.Source is bound to the current item (i.e. the row's DataContext) but it doesn't seem to work.
I prefer to set the second combo's CollectionViewSource (VendorsCollection) thru an Action trigger or handler at the 1st ComboBox's SelectionChange.
The other ComboBoxes in that field don't seem to make a problem as they're all bound to each other, I might use CollectionViewSource.Filter, anyway it's not a problem to access them as they are simple siblings, not like the first one which is a distant cousin located deep in another DataGridCell.
Here is what is what I tried so far:
<DataGrid>
<DataGrid.Resources>
<CollectionViewSource x:Key="CategoriesCollection" Source="{Binding Context.CategoriesList, Source={x:Static Application.Current}, IsAsync=True}" />
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTemplateColumn Header="Category">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock DataContext="{Binding Category}" Text="{Binding Title}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<!--This is the first ComboBox-->
<ComboBox
IsSynchronizedWithCurrentItem="False"
ItemsSource="{Binding Source={StaticResource CategoriesCollection}}"
DisplayMemberPath="Title"
SelectionChanged="cbCategories_SelectionChanged"
SelectedItem="{Binding Category}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Style">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel>
<TextBlock DataContext="{Binding Finish.Style.Vendor}" Text="{Binding Contact.Title}"/>
<TextBlock DataContext="{Binding Finish.Style}" Text="{Binding Title}"/>
<TextBlock Text="{Binding Finish.Title}"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<StackPanel>
<StackPanel.Resources>
<!--I want, that when the user selects a value in the first ComboBox,
the VendorsCollection below should be populated with the selected Category.Vendors,
or alternatively current row's data item.Category.Vendors,
I just donno how to access current row from these resources.-->
<CollectionViewSource x:Key="VendorsCollection" Source="{Binding Vendors, Source={StaticResource CategoriesCollection}}" />
<CollectionViewSource x:Key="StylesCollection" Source="{Binding Styles, Source={StaticResource VendorsCollection}}" />
<CollectionViewSource x:Key="FinishesCollection" Source="{Binding Finishes, Source={StaticResource StylesCollection}}" />
</StackPanel.Resources>
<ComboBox
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Source={StaticResource VendorsCollection}}"
SelectedItem="{Binding Finish.Style.Vendor}"
DisplayMemberPath="Contact.Title"/>
<ComboBox
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Source={StaticResource StylesCollection}}"
SelectedItem="{Binding Finish.Style}"
DisplayMemberPath="Title"/>
<ComboBox
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Source={StaticResource FinishesCollection}}"
SelectedItem="{Binding Finish}"
DisplayMemberPath="Title"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
I just came across your questions. Did you get your problem resolved? I think your question is similar to this one I got. Hope the solution there helps you too.

Problem binding DataGridComboBoxColumn.ItemsSource

I have 3 tables:
Item - which is the DataContext - it has a navigation column Group
Group - has a navigation column Category.
I want to have in the DataGrid both (Category & Group) columns and when I choose a category it should display in the group col only the Category.Groups.
Here is the code I am working on:
<tk:DataGrid AutoGenerateColumns="False" ItemsSource="{Binding}">
<tk:DataGrid.Columns>
<!--Works-->
<tk:DataGridComboBoxColumn
Header="Categroy"
DisplayMemberPath="Title"
SelectedValuePath="CategoryId"
SelectedValueBinding="{Binding Group.Category.CategoryId}"
ItemsSource="{Binding Context.Categories,
Source={x:Static Application.Current}}"
/>
<!--Look at these two things:-->
<!--This does work-->
<tk:DataGridTemplateColumn>
<tk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ItemsControl
ItemsSource="{Binding Group.Category.Groups}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type data:Group}">
<TextBlock Text="{Binding Title}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</tk:DataGridTemplateColumn.CellTemplate>
</tk:DataGridTemplateColumn>
<!--But this does NOT work, even it's the same source-->
<!--Notice I even tried a dummy converter and doesnt reach there-->
<tk:DataGridComboBoxColumn
Header="Group"
DisplayMemberPath="Title"
SelectedValuePath="GroupId"
ItemsSource="{Binding Group.Category.Groups,
Converter={StaticResource DummyConverter}}"
SelectedValueBinding="{Binding Group.GroupId}"
/>
</tk:DataGrid.Columns>
</tk:DataGrid>
Update
Would you say the problem is that the ItemsSource property cannot be set to a non-static Binding?
I suspect so because even I set the ItemsSource to {Binding} with the DummyConverter it doesn't stop in the converter; and in the Category ComboBox it works fine.
The columns in the datagrid don't have a datacontext, as they are never added to the visual tree. sound a bit weird but have a look at vince's blog, its got a good example of the visual layout. once the grid is drawn the cells have a data context and you can set the combo boxes items source in them using normal bindings (not static resources..)
You can access the combo box items source as such:
<dg:DataGridComboBoxColumn>
<dg:DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Path=MyBindingPath}" />
</Style>
</dg:DataGridComboBoxColumn.EditingElementStyle>
</dg:DataGridComboBoxColumn>
Have a look here and also here for some code. You will also need to set the items source for the non edting element as in this post
I was using MVVM and I wanted to bind the ItemSource of the column to a collection of objects in the window data context. I must have tried 10 different ways and nothing worked until I found this answer.
The trick is to define a CollectionViewSource outside the grid and then reference it inside the grid using StaticResource. For example,
<Window.Resources>
<CollectionViewSource x:Key="ItemsCVS" Source="{Binding MyItems}" />
</Window.Resources>
<!-- ... -->
<DataGrid ItemsSource="{Binding MyRecords}">
<DataGridComboBoxColumn Header="Column With Predefined Values"
ItemsSource="{Binding Source={StaticResource ItemsCVS}}"
SelectedValueBinding="{Binding MyItemId}"
SelectedValuePath="Id"
DisplayMemberPath="StatusCode" />
</DataGrid>

Resources