【发布时间】:2015-05-18 21:21:36
【问题描述】:
我对 MVVM 和绑定非常陌生,我正在努力学习如何使用它。 我遇到了将视图模型绑定到视图的问题,特别是将可观察集合绑定到列表框。
这是我的视图模型的样子:
namespace MyProject
{
using Model;
public class NetworkViewModel: INotifyPropertyChanged
{
private ObservableCollection<Person> _networkList1 = new ObservableCollection<Person>();
public ObservableCollection<Person> NetworkList1 //Binds with the listbox
{
get { return _networkList1; }
set { _networkList1 = value; RaisePropertyChanged("_networkList1"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
var handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public NetworkViewModel()
{
_networkList1 = new ObservableCollection<Person>()
{
new Person(){FirstName="John", LastName="Doe"},
new Person(){FirstName="Andy" , LastName="Boo"}
};
}
}
在我看来
namespace MyProject
{
public partial class Networking : Window
{
public Networking()
{
InitializeComponent();
this.DataContext = new NetworkViewModel();
lb1.ItemsSource = _networkList1;
}
}
}
在 XAML 中我有
<ListBox x:Name="lb1" HorizontalAlignment="Left" ItemsSource="{Binding NetworkList1}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock >
<Run Text="{Binding Path=FirstName}"/>
<Run Text="{Binding Path=LastName}"/>
</TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
【问题讨论】:
-
如果您是 MVVM 新手,我强烈建议您考虑使用 MVVM 框架。一个例子(我使用的那个)是 Caliburn.Micro (caliburnmicro.com)。 MVVM 框架让事情变得超级简单,例如自动绑定到视图模型上的公共属性,只需在视图中设置控件的
x:Name以匹配属性名称。
标签: c# wpf mvvm binding viewmodel