最近我发现在我的绑定(bind)中,第二种简化方法与第二种方法一样有效。由于我一直使用第一个,所以我想知道选择其中一个的原因是什么。
带有虚拟私有(private)变量的公共(public)方法
public ObservableCollection<MyDeviceInfo> DiscoveredDevicesList
{
get
{
return _DiscoveredDevicesList;
}
set
{
_DiscoveredDevicesList = value;
OnPropertyChanged("DiscoveredDevicesList");
}
}
private ObservableCollection<MyDeviceInfo> _DiscoveredDevicesList;
自动实现的属性
public ObservableCollection<MyDeviceInfo> DiscoveredDevicesList { get; set; }
最佳答案
它主要指的是ObservableCollection<T>
特性。 Public method with a dummy Private variable
需要通过XAML指定DataContext,例如:
ObservableCollection<T>
public class ViewModel : NotificationObject
{
private ObservableCollection<Person> _myCollection;
public ObservableCollection<Person> MyCollection
{
get
{
return _myCollection;
}
set
{
_myCollection = value;
NotifyPropertyChanged("MyCollection");
}
}
}
XAML
<!-- Set the DataContext in XAML -->
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
<Grid>
<ListBox ItemsSource="{Binding Path=MyCollection}" /> <!-- Or any other control -->
</Grid>
在代码隐藏中使用集合,如下所示:
ViewModel MyViewModel = this.DataContext as ViewModel;
MyViewModel.MyCollection = new ObservableCollection<Person>();
MyViewModel.MyCollection.Add(new Person()
{
Age = 22,
Name = "Nick",
});
在这种情况下,如果集合具有自动属性:
public ObservableCollection<Person> MyCollection
{
get;
set;
}
然后Binding
不起作用,即它不会更新属性集合。但是,如果您设置 DataContext
在代码隐藏中:
this.DataContext = MyViewModel;
Binding
将与自动属性一起使用。
关于c# - 自动实现的属性与自动实现的属性绑定(bind)中的公共(public)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23076319/