I am trying to learn WPF and binding but don't seem to be able to understand what is going on. I have copied a code sample using a combobox and have been trying modifying it to see what happens. The problems appears to be with setting the datacontext. If I set it after InitializeComponent(); with DataContext = this; everything works great. However, I can't get the sample to work with any other DataContext setting. I have tried
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Name="_this" DataContext="{Binding ElementName=_this}"
with no data in my combobox.
The code behind is:
cbItems = new ObservableCollection<ComboBoxItem>();
var cbItem = new ComboBoxItem { Content = "All" };
SelectedItem = cbItem;
cbItems.Add(cbItem);
var items = (from a in dc.Counties
select a.CountyName).ToList();
foreach (var item in items)
{
//cbItems.Add(cbItem);
cbItems.Add(new ComboBoxItem{Content = item});
}
The xaml is
<ComboBox x:Name="ComBoCounty" HorizontalAlignment="Left" Margin="44,38,0,0" VerticalAlignment="Top"
Width="120" ItemsSource="{Binding cbItems}" SelectedItem="{Binding SelectedcbItem}"
Loaded="ComBoCounty_OnLoaded" SelectionChanged="ComBoCounty_OnSelectionChanged" Height="20" />
I use ReSharper and it gives me an indication of an error and has recommendations for DataContext values. I have tried them all with with no data in my combobox. This seems like it is one of the most basic things to understand and I have spent lots of time trying to get it. If someone could show me a way that this could work without setting the DataContext in xaml and why it works I would appreciate it.