2

I am by no means an expert on WPF so this is probably very simple. I'm trying to bind a List to a combobox. It works in code, it doesn't work in xaml. If I remove the ItemsSource from the constructor, it doesn't work, which is how I know. I thought I had the equivalent in xaml, but apparently it's not.

xaml:

    <ComboBox Height="23"
              HorizontalAlignment="Left"
              Margin="146,76,0,0"
              Name="comboBox1"
              VerticalAlignment="Top"
              Width="120"
              ItemsSource="{Binding AvailableActions}"
              DisplayMemberPath="Name"
              SelectedValuePath="Name"
              SelectedValue="Replace" />

constructor:

    public MainWindow()
    {
        _availableActions = new List<IMapperAction>
                       {
                           new ReplaceAction(),
                           new CollapseAction(),
                           new NewBasedOnAction()
                       };

        InitializeComponent();
        Loaded += OnWindowLoaded;

        comboBox1.ItemsSource = AvailableActions;
    }
George R
  • 3,784
  • 3
  • 34
  • 38

2 Answers2

2

Well, you need to set the DataContext of the main window:

public MainWindow()
{
    _availableActions = new List<IMapperAction>
                   {
                       new ReplaceAction(),
                       new CollapseAction(),
                       new NewBasedOnAction()
                   };

    InitializeComponent();
    DataContext = this;
    Loaded += OnWindowLoaded;
}
ChrisWue
  • 18,612
  • 4
  • 58
  • 83
  • Oh I see. Thanks! Why did it work in code? Because it was pushing the context to the xaml rather than doing it from xaml, which would mean needing a context in which to "talk" to? – George R May 20 '11 at 07:21
  • 1
    in works in code because you set the itemsource directly, without binding. – blindmeis May 20 '11 at 07:29
0

As suggested here, you have to set the DataContext.

You can also read this link to know why and when which of the two should be used:

Why are DataContext and ItemsSource not redundant?

Community
  • 1
  • 1
Mamta D
  • 6,310
  • 3
  • 27
  • 41