[英]WPF recursive treeview with MVVM pattern
我是 WPF 和 MVVM 模式的新手。 我正在嘗試將 Treeview 遞歸綁定到 ObservableCollections。 我在這個網站上搜索了很多次,但我沒有找到我的問題的答案。 這是我的 Model class:
public class CategoryCounter
{
public int ID { get; set; }
public string Supplier { get; set; }
public string Name { get; set; }
public Nullable<int> Parent { get; set; }
public ObservableCollection<CategoryCounter> Children => new ObservableCollection<CategoryCounter>(/*some linq code here*/);
和 ViewModel class:
public class CategoriesViewModel : BaseViewModel
{
private string supplier;
private ObservableCollection<CategoryCounter> categories;
public ObservableCollection<CategoryCounter> Categories
{
get { return categories; }
set
{
if (value != categories)
{
categories = value;
}
}
}
public void SetSupplier(string supplier)
{
this.supplier = supplier;
Categories = new ObservableCollection<CategoryCounter>(CategoryContatori.GetRootBySupplier(supplier));
NotifyPropertyChanged();
}
}
現在,當我調用“SetSupplier()”時,集合已填滿,一切正常,但視圖沒有顯示任何內容。 這是 XAML 代碼:
<StackPanel>
<TreeView ItemsSource="{Binding Categories}" HorizontalAlignment="Left" Height="200" VerticalAlignment="Top" Width="250">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type dbModel:CategoryCounter}" ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
</StackPanel>
即使子項是相同的 object,我如何綁定它們? 這是問題嗎? 感謝您的耐心等待。
嘗試直接設置模板
<TreeView ItemsSource="{Binding Categories}" HorizontalAlignment="Left" Height="200" VerticalAlignment="Top" Width="250">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
資源通常需要位於需要訪問它們的項目的父項中。
編輯:雖然剛剛進行了快速搜索,但 TreeViews 可能並非如此,因此 INPC 很可能是您的問題,正如評論中已經指出的那樣。
在Categories
屬性的設置器中提高PropertyChanged
:
private ObservableCollection<CategoryCounter> categories;
public ObservableCollection<CategoryCounter> Categories
{
get { return categories; }
set
{
categories = value;
NotifyPropertyChanged(nameof(Categories));
}
}
還要確保Categories
屬性和Children
屬性返回CategoryCounter
對象的具體化 collections。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.