so I have a custom class in a list. I can’t seem to get the list and a combobox to bind though. The list should display all the name values of the customclass. I want to do this in code. Any help most appreciated (as ever!).
It’s best if I give some code snippets I think.
The class:
public class Asset : IComparable<Asset>
{
...
public String name { get { return _name; } set { _name = value; } }
...
}
List and my attempted binding, is it that ComboBox.ItemBindingGroupProperty is the wrong thing?
List<Asset> assetsForCbos = new List<Asset>();
assetsForCbos.Add(new Asset("example asset"));
Binding bindingAssetChoice = new Binding();
bindingAssetChoice.Source = assetsForCbos;
bindingAssetChoice.Path = new PropertyPath("name");
bindingAssetChoice.Mode = BindingMode.OneWay;
cboAsset1.SetBinding(ComboBox.ItemBindingGroupProperty, bindingAssetChoice);
In the XAML I have
<ComboBox Height="23"
ItemsSource="{Binding}"
HorizontalAlignment="Left"
Margin="10,8,0,0"
Name="cboAsset1"
VerticalAlignment="Top"
Width="228"
IsReadOnly="True"
SelectedIndex="0"/>
What you can try is in xaml set
ItemsSource="{Binding}"and in code behind setPersonally my preference is to do all binding in Xaml so if there is a change needed i just have to look at the xaml.
EDIT: If you wanted to show the name property, instead of Namespace.Asset, you could of done one of the following
Note: This will not change, therefore if the name changes in the Asset object, this will not update in the view.
Create a DataTemplate which contains a StackPanel(light weight layout container of my choice) and a TextBlock inside the StackPanel which binds to the name property. As your creating the ComboBox in code here is how you could do it.