nikotromus
nikotromus

Reputation: 1074

xaml databinding in c#

I am pretty sure the code looks right based on an example I am mimicking, but the combo box is empty when I run the program. What am I doing wrong here?

xaml:

 <ComboBox Grid.Column="1"  Width="200" Height="20"  
           x:Name="cBox" 
           ItemsSource="{Binding DummyClassCollection}" 
           DisplayMemberPath="DisplayValue" />

Code Behind:

 public partial class PlayerPromptPage : Page
    {
        public PlayerPromptPage()
        {
            InitializeComponent();           
        }                

        public ObservableCollection<DummyClass> DummyClassCollection {
            get {
                return new ObservableCollection<DummyClass>
                {
                    new DummyClass{DisplayValue = "Item1", Value = 1},
                    new DummyClass{DisplayValue = "Item3", Value = 3},
                    new DummyClass{DisplayValue = "Item2", Value = 2},
                    new DummyClass{DisplayValue = "Item4", Value = 4},
                };
            }
        }
    }


    public class DummyClass
    {
        public int Value { get; set; }
        public string DisplayValue { get; set; }
    }

Upvotes: 0

Views: 30

Answers (1)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43936

You need to set the DataContext for the page.
This can easily be done in the constructor:

public PlayerPromptPage()
{
    InitializeComponent();           
    DataContext = this;
}

Alternativly you can set the DataContext in XAML:

<Window  
    ...
    DataContext="{Binding RelativeSource={RelativeSource Self}}"

Upvotes: 2

Related Questions