找不到我的项目ViewModel元素。我正在尝试在WPF Usercontrol中实现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;
}
}
答案 0 :(得分:1)
您错过了在ViewModel中实现INotifyPropertyChanged接口,binded属性需要将“刷新消息”发送到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));
}
}
}
答案 1 :(得分:1)
根据您的代码,TypeName为null,因此您在Label上看不到任何内容。从您的代码中,我认为您想描述如下:
public string TypeName
{
get{ return SelectedType.Name.ToString();}
}
正如deryck建议的那样,您应该添加INotifyPropertyChanged接口以进行通知,但它不应该首次影响绑定。如果您认为ViewModel的数据正确但未在UI上填充,则应检查DataContext和Binding。