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.