Arp*_*ara 3 c# data-binding wpf datacontext mvvm
我是 wpf c# 的新手,正在尝试一些示例应用程序,问题是当我DataContext在 xaml 中提到时,它InitializeComponent被递归调用并显示
mscorlib.dll 中发生 System.StackOverflowException
这是我的 XAML 标记:
<Window x:Class="Company1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Company1"
Title="MainWindow" Height="350" Width="525" >
<Window.DataContext>
<local:MainWindow/>
</Window.DataContext>
<Grid>
<GroupBox Margin="5,5,5,5" Background="Beige">
<Grid>
<StackPanel>
<Button Width="80" Height="25" Margin="10,10,10,10"
Content="Employee" Command="{Binding ButtonCommand}"
DataContext="{Binding }">
</Button>
</StackPanel>
<DataGrid
Name="myGridView" Margin="5,69,5,5"
Width="Auto" AutoGenerateColumns="True"
AlternatingRowBackground="Bisque">
<DataGrid.Columns>
<DataGridTextColumn Header="Name"
Binding="{Binding Path=EmpName}"
Width="*" IsReadOnly="True"/>
<DataGridTextColumn Header="ID"
Binding="{Binding Path=EmpId}"
Width="*" IsReadOnly="True"/>
<DataGridTextColumn Header="Place"
Binding="{Binding Path=Location}"
Width="*" IsReadOnly="False"/>
<DataGridTextColumn Header="Dept"
Binding="{Binding Path=Department}"
Width="*" IsReadOnly="True"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</GroupBox>
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
XAML.cs:
private ICommand m_ButtonCommand;
public ICommand ButtonCommand
{
get { return m_ButtonCommand; }
set { m_ButtonCommand = value; }
}
public MainWindow()
{
InitializeComponent();
ButtonCommand = new RelayCommand(new Action<object>(ShowEmployees));
}
Run Code Online (Sandbox Code Playgroud)
如果您使用 xaml.cs 中的属性,则不需要提供数据上下文,因为它是相同的部分类
当您将数据上下文设置为 MainWindow 时,它会创建 MainWindow 的另一个实例,并尝试将其数据上下文设置为 MainWindow。因此,进入无限循环会给出 stackoverflow 异常。
在 codeproject 中了解有关 DataContext 属性的更多信息在代码项目DataContext in WPF
如果您使用另一个类作为视图模型,那么您需要通过定位器提供数据上下文
<Window x:Class="Company1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Company1"
Title="MainWindow" Height="350" Width="525"
DataContext={Binding Path=MainWindowViewModel, StaticResource locator} >
Run Code Online (Sandbox Code Playgroud)
定位器将是 Resources.xaml 中的资源,如下所示
<MVVM:MainPageViewModelLocator x:Key="locator" />
Run Code Online (Sandbox Code Playgroud)
您可以在 geekchamp使用来自 MVVM-Light 的简单 ViewModelLocator中获取定位器类和有关 MVVM 模式的更多详细信息
| 归档时间: |
|
| 查看次数: |
2812 次 |
| 最近记录: |