我有一个关于 WPF MVVM 如何工作和有工作代码的问题,但不确定它为什么工作。大多数在线教程似乎都提供了使用单个窗口的示例,所以我不确定我是否使用多个窗口/页面/用户控件正确执行此操作。
如果我有一个名为的类ViewModel
并且我使用下面的代码设置DataContext
了MainWindow
,那么我设置DataContext
了MainWindow
唯一的。
MainWindow.xaml.cs:
public partial class MainWindow
{
Private ViewModel viewModel = new ViewModel();
public MainWindow()
{
InitializeComponent();
this.DataContext = this.viewModel;
}
}
如果我然后创建一个新的用户控件,然后绑定一个 DataGrid 而不指定 viewModel 的路径,为什么下面的代码在我没有设置用户控件的情况下工作DataContext
?
这是 WPF 的工作方式还是我也应该在用户控件中设置 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");
}
}
}
用户控件.xaml.cs:
public partial class MainSignals : UserControl
{
public MainSignals()
{
InitializeComponent();
//this.DataContext = new ViewModel(); //WORKS WITHOUT THIS??
}
}