Dr. Thomas C. King
Dr. Thomas C. King

Reputation: 1034

WPF Binding a List<custom> to a combobox in C# code?

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"/>

Upvotes: 2

Views: 2284

Answers (1)

Michal Ciechan
Michal Ciechan

Reputation: 13888

What you can try is in xaml set ItemsSource="{Binding}" and in code behind set

cboAsset1.DataContext = assetsForCbos;

Personally 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

  1. Override ToString in the Asset class to return the asset name.
    Note: This will not change, therefore if the name changes in the Asset object, this will not update in the view.
  2. 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.

    // Create Data Template
    DataTemplate itemsTemplate = new DataTemplate();
    itemsTemplate.DataType = typeof (Asset);
    
     // Set up stack panel
     FrameworkElementFactory sp = new FrameworkElementFactory(typeof (StackPanel));
     sp.Name = "comboStackpanelFactory";
     sp.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
    
     // Set up textblock
     FrameworkElementFactory assetNameText = new FrameworkElementFactory(typeof (TextBlock));
     assetNameText.SetBinding(TextBlock.TextProperty, new Binding("name"));
     sp.AppendChild(assetNameText);
    
     // Add Stack panel to data template
     itemsTemplate.VisualTree = sp;
    
     // Set the ItemsTemplate on the combo box to the new data tempalte
     comboBox.ItemTemplate = itemsTemplate;
    

Upvotes: 3

Related Questions