【发布时间】:2019-02-18 15:29:02
【问题描述】:
我是 WPF 世界的新手,刚开始阅读 WPF。在阅读时,我发现每当我们将某些元素绑定到该属性后面的代码中的属性时,该属性始终需要是公共的,并且即使该属性位于 xaml.cs 文件中,也需要设置 DataContext。但是订阅事件的方法可以是私有的。
例如: 在以下示例中,SelectedCountryIndex 属性是公共的,但 Country_SelectionChanged 方法是私有的。
xaml 文件:
<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){}
}
现在根据this post Mainwindow.xaml.cs 的类与 MainWindow.xaml 的类一样是部分的,因此我们可以直接编写 Country.SelectionChanged+=Country_SelectionChanged 现在 Country_SelectionChanged 可以是私有的。 但是为什么绑定不会发生这种情况?如果我们将属性设置为公开,那么只有代码有效。
【问题讨论】: