2013-09-05 51 views
0

我在WPF中顯示第一級任務列表中的TreeView控件。每個任務都有一個人員列表。任務和人員都存儲在數據庫中。我編寫了2個封裝了Linq2Sql類的viewmodel類。 TreeView由2個分層的DataTemplates組成,它們引用視圖模型類。顯示數據效果很好,我可以添加任務和人員沒有任何問題。從Linq2Sql綁定刪除子項目TreeView

但現在我遇到了問題,我想從contextmenu中刪除任務下的人員。我的問題是我無法訪問父任務,因此無法更新個人集合。我知道要刪除哪個人,但不知道它屬於哪個任務。

達到此目的的最佳方法是什麼?

謝謝!

格里特

using System; 

class ViewmodelPerson 
{ 
    public ViewmodelPerson(LinqPerson P) 
    { 
     DBPerson = P; 
    } 
    LinqPerson DBPerson; 
} 

public class ViewmodelTask 
{ 

    public ViewmodelTask(LinqTask DBTask) 
    { 
     this.DBTask = DBTask; 
     _Persons = from P in DBTask.Person 
        select new ViewModelPerson(P); 
    } 

    LinqTask DBTask; 

    List<ViewmodelPerson> _Persons; 
    List<ViewmodelPerson> Persons 
    { 
     get 
     { 
      return _Persons; 
     } 
    } 

    public void AddPerson(ViewmodelPerson P) 
    { 

    } 
} 

class BaseViewModel 
{ 
    public List<ViewmodelTask> Tasks 
    { 
     get 
     { 
      // Code to get the tasks from Database via Linq 
     } 
    } 
} 

SOLUTION 因爲我沒能得到該人屬於我只是增加了一個成員ParentTask我個人類的父任務。這個成員需要在構造函數中傳遞。當在ViewmodelPerson類上調用DeletePerson方法時,Object在數據庫中被刪除,並且我可以訪問父Task對象,並且可以清理List。然後調用IPropertyChanged的ChangedProperty(「Persons」),WPF整理UI就像魔術一樣!

我只是想知道如果這個方法對內存消耗有很大影響,如果有很多人和任務。

回答

0

如果我理解正確,你有一個ContextMenu,但是你不能從其範圍訪問你的視圖的DataContext。這是WPF中一個普遍的問題,解決的辦法就是「把DataContext」成Tag的性質,我們以後可以從ContextMenu檢索:

<DataTemplate DataType="{x:Type YourNamespace:YourDataType}"> 
    <Border Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType={ 
x:Type YourViewNamespace:NameOfThisControl}}}" ContextMenu="{StaticResource 
YourContextMenu}"> 
     ... 
    </Border> 
</DataTemplate> 

然後,你需要這個Tag屬性設置爲的的DataContextContextMenu使用一個方便的屬性命名PlacementTarget

<ContextMenu x:Key="YourContextMenu" DataContext="{Binding PlacementTarget.Tag, 
RelativeSource={RelativeSource Self}}"> 
    <MenuItem Header="First Item" Command="{Binding CommandFromYourViewModel}" /> 
</ContextMenu> 

要了解更多信息,請大家看看Context Menus in WPF崗位上WPF Tutorial.NET。

+0

感謝您的解決方案。我已經閱讀過這個解決方案,但對我來說似乎不太方便。我在第一篇文章中提到的方式解決了它。不管怎麼說,還是要謝謝你! –