2013-10-12 40 views
0

我有一個關於WPF MVVM是如何工作並有工作代碼的問題,但不知道爲什麼它可以工作。大多數在線教程似乎都給出了使用單個窗口的示例,因此我不確定是否使用多個窗口/頁面/用戶控件正確執行此操作。如何在多個Windows/Pages/Controls上設置DataContext?

如果我有一個類名爲ViewModel和我使用下面的代碼設置DataContextMainWindow,然後我設置只有MainWindowDataContext

MainWindow.xaml.cs:

public partial class MainWindow 

{ 
    Private ViewModel viewModel = new ViewModel(); 

    public MainWindow() 
    { 
     InitializeComponent(); 
     this.DataContext = this.viewModel; 
    } 

} 

如果我再創建一個新的用戶控件,然後綁定一個DataGrid但沒有指定視圖模型的路徑,爲什麼下面的工作代碼的時候我還沒有設置usercontrol的DataContext

這是WPF的工作原理,還是我應該在usercontrol中設置DataContext?什麼是正確的方法來做到這一點?

MainSignals.xaml:

<UserControl x:Class="ProjectXYZ.Content.MainSignals" 
      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:core="clr-namespace:System;assembly=mscorlib" 
      xmlns:local="clr-namespace:ProjectXYZ.Content" 
      xmlns:mui="http://firstfloorsoftware.com/ModernUI" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300" > 
    <Grid> 
     <DockPanel> 
      <DataGrid Name="DG1" ItemsSource="{Binding ReceivedSignals}" > 
       <DataGrid.Columns> 
        <mui:DataGridTextColumn Header="SignalID" Binding="{Binding signalID}"/> 
      <mui:DataGridTextColumn Header="SignalType" Binding="{Binding signalType}"/> 
       </DataGrid.Columns> 
      </DataGrid> 
     </DockPanel> 
    </Grid> 
</UserControl> 

ViewModel.cs:

private ObservableCollection<MainWindow.SignalVar> _receivedSignals; 

Public ViewModel() 
{ 
} 

public event PropertyChangedEventHandler PropertyChanged; 


// Create the OnPropertyChanged method to raise the event 
protected void OnPropertyChanged(string name) 
{ 
    PropertyChangedEventHandler handler = PropertyChanged; 
    if (handler != null) 
    { 
     handler(this, new PropertyChangedEventArgs(name)); 
    } 
} 

public ObservableCollection<MainWindow.SignalVar> ReceivedSignals 
{ 
    get { return _receivedSignals; } 
    set 
    { 
     if (value != _receivedSignals) 
     { 
      _receivedSignals = value; 
      OnPropertyChanged("ReceivedSignals"); 
     } 
    } 
} 

UserControl.xaml.cs:

public partial class MainSignals : UserControl 
{ 

    public MainSignals() 
    { 
     InitializeComponent(); 
     //this.DataContext = new ViewModel(); //WORKS WITHOUT THIS?? 
    } 

} 

回答

2

釷是由於子控件繼承其父母的DataContext(如果DataContext沒有明確設置)。對於某些DependancyProperties,這是如此,例如,如果設置父控件的前景,則所有子控件都繼承相同的Foreground屬性值。

就你的情況而言,因爲你沒有明確地爲子控件UserControl設置DataContext,它將採用它的父級的DataContext,這是你的Window在這裏。

相關問題