爲什麼數據綁定可以在設計器中看到: Click to show image: Databinding seems OK 但運行時不顯示任何內容? Click to show image: No Data, no usercontrol?MVVM DataBinding確定在Designer中,而不是在運行時
大綱代碼結構:
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:模型類ID /名稱/描述屬性
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
public 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可以在第一鏈接圖像中上方觀察,請注意在上面的未命中線斷點)。用戶控件位於ObservableCollection的一部分Tabcontrol中。我不認爲這是數據綁定中的問題。如果需要,將張貼標籤的代碼。
「調試輸出」窗口中沒有任何錯誤指出數據綁定失敗的原因。
後您的TabControl的XAML。它的DataContext是什麼? – mm8
UserControls應該爲您的模型或您的視圖模型設計。你不應該爲你的UserControl設計一個視圖模型。 TextBox是否有TextBoxViewModel?不,有一個很好的理由。有關更多詳細信息,請參閱此答案。(https://stackoverflow.com/a/44729258/1228)此外,您始終可以使用Snoop等工具在運行時檢查綁定。它會告訴你,父視圖模型是由用戶控件繼承的,它取代了SitesViewModel。 – Will