Reputation: 51094
I have a ComboBox marked up as:
<ComboBox x:Name="TitleCombo"
Width="100"
Height="20"
DisplayMemberPath="TITLE_NAME"
SelectedValuePath="TITLE_CODEID"
DataContext="{Binding}"
ItemsSource="{Binding Path=Titles}" />
It is the sole control on NoticeWindow.xaml
, which has the following code-behind:
public partial class NoticeWindow : Window
{
private readonly Xt900Context _dbContext = new Xt900Context();
public NoticeWindow()
{
InitializeComponent();
var tits = _dbContext.TITLEs.ToList();
Titles = new ObservableCollection<TITLE>(tits);
DataContext = this;
TitleCombo.ItemsSource = Titles;
}
ObservableCollection<TITLE> Titles { get; set; }
}
Without the TitleCombo.ItemsSource = Titles
statement, the ComboBox remains blank. Why is this?
Upvotes: 0
Views: 121
Reputation: 6547
So, your ComboBox
is inside NoticeWindow
, which has it's DataContext
set to himself.
This is also where you defined the Titles
property.
Like @AirL pointed out, Titles
should be marked as Public
:
public ObservableCollection<TITLE> Titles { get; set; }
Also, there is no need defining a DataContext
on the ComboBox
nor stating TitleCombo.ItemsSource = Titles;
Since the ComboBox
inherits its DataContext
from the NoticeWindow
. You can just bind it to the Titles
property
<ComboBox x:Name="TitleCombo"
Width="100"
Height="20"
DisplayMemberPath="TITLE_NAME"
SelectedValuePath="TITLE_CODEID"
ItemsSource="{Binding Titles}" />
Upvotes: 2
Reputation: 1917
In the code you provided to us, your ObservableCollection<TITLE> Titles { get; set; }
is defined as private
(no access modifier being defined and private
being the default one).
Given WPF databinding only works with public properties (see MSDN related documentation), it could explain why your binding isn't working properly and that you need to explicitly set your ItemsSource
in code behind to fill your ComboBox
.
The properties you use as binding source properties for a binding must be public properties of your class. Explicitly defined interface properties cannot be accessed for binding purposes, nor can protected, private, internal, or virtual properties that have no base implementation.
Upvotes: 0