2015-09-29 50 views
0

我目前正在寫一在其左側的導航面板(而我綁定navigationViewModel),並在其右側的內容展示器(我綁定到一個WPF應用程序前面提到的虛擬機的用戶控件構件「CurrentView」。 對於該導航面板的每一個項目,我創建一個相應的用戶控制,並且對於每個這些用戶控制的,我結合相應的視圖模型的一個實例。WPF,MVVM和應用範圍的資源最佳實踐

點擊導航面板的項目將其ViewModel的UserControl成員CurrentView設置爲相應UC的實例,然後將其顯示在上面提到的內容展示器中。

第一個導航項目是一些「選擇或創建一個新客戶」的形式。當這個操作完成後,我想設置一些寬的應用程序資源ID,我將綁定其他導航項Enabled狀態。因此,如果廣泛的應用程序資源爲空,則只要將其設置爲任何內容,它們都將被禁用,它們將被啓用。還會有一些機制允許相應的ViewModel被通知這種情況。

我想知道這是否會被認爲是一種良好的做法? 此外,我想知道如果我可以簡單地在app.xaml中聲明一個int資源並將其綁定到導航項Enabled屬性,將該資源設置爲立即刷新此屬性?還是有更好,更簡單或更清潔的方式?

回答

1

另一種可能是窩兩個的ViewModels(導航和currentview)在第三視圖模型(說mainviewmodel)

那麼這個主視圖模型可以保持狀態,應該是在這些的ViewModels和整個currentviews的情況下可用。

這樣您就不需要在應用程序中擁有全局狀態,並且可以簡單地將Window的datacontext設置爲主視圖模型,並將導航和內容視圖綁定到主視圖模型的屬性。

這也允許你有一個適當的地方導航到不同的內容視圖。

+0

感謝您的回覆,其讓我思考!我發佈了我最終做的,不知道它是乾淨的,但它的工作原理... – Louitbol

0

這是我最終做的:

在我的app.xaml;我聲明如下資源:

<Application x:Class="MyProject.GUI.App" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:vm="clr-namespace:MyProject.GUI.ViewModels" 
      StartupUri="MainWindow.xaml"> 
    <Application.Resources> 
     <vm:MainViewModel x:Key="MainViewModel" /> 
    </Application.Resources> 
</Application> 

這MainViewModel公開靜態屬性如下:

static bool _myStaticProperty; 
public static bool MyStaticProperty 
{ 
    get 
    { 
     return _myStaticProperty; 
    } 
    set 
    { 
     _myStaticProperty = value; 
     NotifyStaticPropertyChanged("MyStaticProperty"); 
    } 
} 

而下面的靜態INPC機制:

#region Static property INPC mechanism 
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged; 
static void NotifyStaticPropertyChanged(string propertyName) 
{ 
    if (StaticPropertyChanged != null) 
    { 
     StaticPropertyChanged(null, new PropertyChangedEventArgs(propertyName)); 
    } 
} 
#endregion  

和我不同的ViewModels:

FirstChildViewModel _firstChildViewModel; 
public FirstChildViewModel FirstChildViewModel 
{ 
    get 
    { 
     if (_firstChildViewModel == null) 
      _firstChildViewModel = new FirstChildViewModel(); 
     return _firstChildViewModel; 
    } 
} 
//then a second one, a third one and so on 

哪些是綁定到我的用戶控件遵循

<UserControl x:Class="MyProject.GUI.Views.FirstChildControl" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:local="clr-namespace:MyProject.GUI.ViewModels" 
     mc:Ignorable="d" 
     DataContext="{Binding Path=FirstChildViewModel, 
           Source={StaticResource MainViewModel}}"> 

在我的用戶控件的XAML代碼,我宣佈命令綁定等,這些基本上做的是在他們的視圖模型以下

MainViewModel.MyStaticProperty = myBoolValue;