找不到ViewModel数据
本文关键字:数据 ViewModel 找不到 | 更新日期: 2023-09-27 18:19:40
找不到我的项目ViewModel元素。我正试图在我的WPF用户控件中实现一个ViewModel。但是,绑定工作不正常,并且似乎没有数据。我正在尝试创建一个与之交互的ViewModel,将通用字符串数组和其他各种数据放入其中。
MainWindow.xaml-(用户控制声明)
<panels:FilterLister Grid.Column="0" x:Name="filter1FilterLister" />
MainWindows.cs-(在构造函数中,调用usercontrol
filter1FilterLister.Initialise(typeof(Genre));
FilterListViewModel.cs
public class FilterListViewModel
{
MyEntities context = new MyEntities();
ObservableCollection<string> entries = new ObservableCollection<string>();
public Type SelectedType;
private string p_TypeName;
public string TypeName
{
get { return p_TypeName; }
set {
//p_TypeName = value;
p_TypeName = SelectedType.Name.ToString();
}
}
public FilterListViewModel() { }
public FilterListViewModel(Type selectedType)
{
if (selectedType == typeof(Artist))
{
returnedArray = Artist.ReturnArtistNames(context);
}
// put together ObservableCollection
foreach (var str in returnedArray)
{
entries.Add(str);
}
SelectedType = selectedType;
}
}
FilterLister.xaml
<Label Name="labelToBind" Content="{Binding TypeName}" Grid.Row="0" />
FilterLister.cs
public partial class FilterLister : UserControl
{
FilterListViewModel filterListViewModel;
private MyEntities context;
public FilterLister()
{
InitializeComponent();
context = new MyEntities();
}
public void Initialise(Type objectType)
{
filterListViewModel = new FilterListViewModel(objectType);
this.DataContext = filterListViewModel;
}
}
根据您的代码,TypeName为null,因此您在Label上没有看到任何内容。从你的代码来看,我想你想描述一下:
public string TypeName
{
get{ return SelectedType.Name.ToString();}
}
正如deryck所建议的,您应该添加INotifyPropertyChanged接口进行通知,但它不应该在第一时间影响绑定。如果您认为ViewModel的数据是正确的,但没有在UI上填充,则应该检查DataContext和Binding。
您在ViewModel中错过了INotifyPropertyChanged接口的实现,它需要绑定的属性才能向UI发送"刷新消息"。
以下是接口,以及如何实现:http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx
public class FilterListViewModel : INotifyPropertyChanged
{
MyEntities context = new MyEntities();
ObservableCollection<string> entries = new ObservableCollection<string>();
public Type SelectedType;
private string p_TypeName;
public string TypeName
{
get { return p_TypeName; }
set {
//p_TypeName = value;
p_TypeName = SelectedType.Name.ToString();
NotifyPropertyChanged();
}
}
public FilterListViewModel() { }
public FilterListViewModel(Type selectedType)
{
if (selectedType == typeof(Artist))
{
returnedArray = Artist.ReturnArtistNames(context);
}
// put together ObservableCollection
foreach (var str in returnedArray)
{
entries.Add(str);
}
SelectedType = selectedType;
}
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}