Reputation: 11
I am new to WPF world and just started reading WPF. While reading I found whenever we bind some Element to property in code behind that property always needs to be public and DataContext needs to be set even if that property lies in xaml.cs file. But the method subscribed to the event can be private.
For ex: In following example SelectedCountryIndex property is public but Country_SelectionChanged method is private.
xaml file:
<ComboBox Name="Countries" SelectedIndex="{Binding SelectedCountryIndex}" SelectionChanged="Country_SelectionChanged"/>
xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
public int SelectedCountryIndex{ get; set; } = 0;
private void Country_SelectionChanged(object sender, SelectionChangedEventArgs e){}
}
Now as per this post Mainwindow.xaml.cs's class is partial like MainWindow.xaml's class hence it is straight that we can write Countries.SelectionChanged+=Country_SelectionChanged and now Country_SelectionChanged can be private. But why this does not happen with binding? If we set property as public then only code works.
Upvotes: 0
Views: 634
Reputation: 1140
Binding is done using reflection to figure out public properties on the DataContext type. This is because your DataContext can be a different class than the view, usually a View Model class in MVVM scenarios.
Your event handler on the other hand is always in the same class, and the access modifier private
is good enough to access this.
Upvotes: 0
Reputation: 9089
There's a slight misunderstanding. private void Country_SelectionChanged(...)
is not your event; it is merely the handler for the event. There is still a public event of SelectionChanged.
Take for instance INotifyPropertyChanged
. It has an event like so:
public event PropertyChangedEventHandler PropertyChanged;
The event
is what you are actually using when you do PropertyChanged += MyFooHandler
.
MyFooHandler
can be public, private, internal, etc. It doesn't matter what the accessor is, but the event needs to have the proper visibility to allow for things to wire into it.
Properties for WPF binding need to be public so that the framework itself can easily see it and work its magic. There's much more behind the scenes than just having {Binding Foo}
. ;)
Upvotes: 3