为什么可以在设计器中看到数据绑定: Click to show image: Databinding seems OK 但运行时没有显示? Click to show image: No Data, no usercontrol?
大纲代码结构:
ViewModelBase:继承自INotofyPropertychanged
的基类 public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = "")
{
if (EqualityComparer<T>.Default.Equals(storage, value))
return false;
storage = value;
this.OnPropertyChanged(propertyName);
return true;
}
}
SiteViewModel:具有标识/名称/描述属性的模型类
public class SiteViewModel : ViewModelBase
{
private int _SiteID;
private string _Name;
private string _Description;
public int SiteID
{
get { return _SiteID; }
set { SetProperty(ref _SiteID, value); }
}
public string Name
{
get { return _Name; }
set { SetProperty(ref _Name, value); }
}
public string Description
{
get { return _Description; }
set { SetProperty(ref _Description, value); }
}
}
SitesViewModel:SiteViewModel的ObservableCollection
public class SitesViewModel : ViewModelBase
{
private ObservableCollection<SiteViewModel> _AllSites;
public ObservableCollection<SiteViewModel> AllSites {
get { return _AllSites; }
set { SetProperty<ObservableCollection<SiteViewModel>>(ref _AllSites, value); }
}
public SitesViewModel()
{
AllSites = new ObservableCollection<SiteViewModel>();
for (int count = 1; count <= 3; count++)
{
AllSites.Add(new SiteViewModel { SiteID = count, Name = "Test" + count.ToString(), Description = "Site:" + count.ToString() } );
}
}
}
SiteManagerControl:具有SitesViewModel属性_AllSites
的UserControlpublic partial class SiteManagerControl : UserControl
{
private SitesViewModel _AllSites;
public SitesViewModel AllSites
{
get { return _AllSites; } //<-- Breakpoint not hit!
set {
if (_AllSites != value)
{ _AllSites = value;
OnPropertyChanged("AllSites");
}}
}
public SiteManagerControl(){
_AllSites = new SitesViewModel();}
(XAML可以在上面的第一个链接图中看到,注意断点不在上面的命中行)。用户控件托管在Tabcontrol中,该控件是ObservableCollection的一部分。我不认为这是数据绑定中的问题。如果需要,将发布标签的代码。
“调试输出”窗口中没有错误指示数据绑定失败的原因。
答案 0 :(得分:0)
您的listview DataContext数据绑定是来自类的对象(SitesViewModel) 此类具有名为(AllSites)的属性,该属性具有名为(AllSites)的oveservable集合属性。
所以我认为您必须在列表视图中修复ItemSource绑定,如下所示:
ItemsSource="{Binding AllSites.AllSites}"
答案 1 :(得分:0)
Will的评论(谢谢!)上面指出了我正确的方向:更改了MainWindow.xaml以包含:
<DataTemplate DataType="{x:Type vm:SitesViewModel}">
<uc:SitesView></uc:SitesView>
</DataTemplate>
此后:http://codingtales.blogspot.co.uk/2010/02/creating-complete-tabbed-interface-in.html重新设计我的标签界面