0

In the code behind I have a private List<string> _materials I would like to display in a combox.

I need to create the data binding in Parts from the Code behind, since I'm filling _materials through a background worker:

public partial class MainWindow : Window
{

    private List<string> _materials;

    public MainWindow()
    {
        InitializeComponent();


    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        BackgroundWorker worker = new BackgroundWorker();
        worker.RunWorkerCompleted += worker_RunWorkerCompleted;
        worker.DoWork += worker_DoWork;
        worker.RunWorkerAsync();
    }

    void worker_DoWork(object sender, DoWorkEventArgs e)
    {         

        _materials = DataSupplier.GetMaterials();
    }

    void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        //Do Databinding Here

        wpMaterial.DataContext = _materials;
        cmbMaterial.ItemsSource = _materials;      


    }

XAML Looks like this:

<WrapPanel x:Name="wpMaterial" >
                            <Label  Content="Material: " FontStyle="Italic" FontFamily="Arial" Foreground="Black" Background="{x:Null}" Width="100" />
                            <ComboBox Name="cmbMaterial">
                                <ComboBox.ItemTemplate>
                                    <DataTemplate>
                                        <StackPanel Orientation="Horizontal">
                                            <TextBlock Text="{Binding Path=Name}" />
                                            <TextBlock Text="Hi" />
                                        </StackPanel>
                                    </DataTemplate>
                                </ComboBox.ItemTemplate>
                            </ComboBox>
                        </WrapPanel>

"Hi" is displayed for every entry i have in my _materials list, but the actual Name is not displayed. So What do I need to put in Text="{Binding ???}" to get my string content displayed?

alexo
  • 936
  • 8
  • 16
KarlW
  • 37
  • 1
  • 6
  • have you tried this? http://stackoverflow.com/questions/20343706/error-when-binding-wpf-combobox-itemssource-to-an-array-of-strings – alexo Dec 09 '14 at 11:01

2 Answers2

2

Because _materials is a list of string it means each item will be of string type so you want to bind to current DataContext of ComboBoxItem.

You can either use {Binding} or {Binding Path=.}

<DataTemplate>
   <StackPanel Orientation="Horizontal">
      <TextBlock Text="{Binding}" />
      <TextBlock Text="Hi" />
   </StackPanel>
</DataTemplate>

From MSDN

Optionally, a period (.) path can be used to bind to the current source. For example, Text="{Binding}" is equivalent to Text="{Binding Path=.}".

dkozl
  • 32,814
  • 8
  • 87
  • 89
1

Since the ItemsSource you binding is just a string collection, you just need to specify Text="{Binding}".

Jawahar
  • 4,775
  • 1
  • 24
  • 47