我正在开发一个执行应用程序。我的应用采用 MVVM。我正在尝试创建一个带有两个用户控件的窗口,其中一个用户控件包括一个从 viewmodel 获取其数据的数据网格。
我希望当应用程序运行时数据网格会自动填充我的默认值(私有文件)。但是存在绑定错误:System.Windows.Data 错误:4:无法使用引用“ElementName=windowView”找到绑定源。绑定表达式:路径=ActivePacket;数据项=空;目标元素是'DataGrid'(名称='dataGrid1');目标属性是“ItemsSource”(类型“IEnumerable”)
谢谢!
这是我的代码:
========= MainWindow.xaml =================
<Window x:Class="Project.Abc.Try.MainWindow"
x:Name="windowView"
xmlns:local="clr-namespace:Project.Abc.Try"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="600">
<Window.DataContext>
<local:PayloadViewModel />
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="78*" />
<RowDefinition Height="233*" />
</Grid.RowDefinitions>
<local:CmdMenuView Grid.Row="0" Margin="6,6,3,6" />
<local:PayloadView Grid.Row="1" Margin="6,6,3,6" />
</Grid>
</Window>
============ PayloadView.xaml ===========
<UserControl x:Class="Project.Abc.Try.PayloadView"
x:Name="PLview"
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"
mc:Ignorable="d"
d:DesignHeight="199" d:DesignWidth="588" >
<Grid Height="200" Width="580" >
<!--<DataGrid AutoGenerateColumns="False" Height="45" HorizontalAlignment="Left" Margin="36,20,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="500" ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=ActivePacket}"> -->
<DataGrid AutoGenerateColumns="False" Height="45" HorizontalAlignment="Left" Margin="36,20,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="500" ItemsSource="{Binding ElementName=windowView, Path=ActivePacket}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding PacketId, Mode=TwoWay}" Header="PacketID " Width="*" />
<DataGridTextColumn Binding="{Binding PacketLength, Mode=TwoWay}" Header="PacketLength" Width="*" />
<DataGridTextColumn Binding="{Binding Spare}" Header="Byte 6" Width="*" />
</DataGrid.Columns>
</DataGrid>
<Button Content="Send" Command="{Binding Path=SendCommand}" Height="23" HorizontalAlignment="Left" Margin="310,122,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
</Grid>
</UserControl>
=================== PayloadViewModel.cs ========================
namespace Project.Abc.Try
{
public class PayloadViewModel : ObservableObject
{
// ......
private CmdPacket _activePacket;
public CmdPacket ActivePacket
{
get { return _activePacket; }
set
{
if (value != _activePacket)
{
_activePacket = value;
OnPropertyChanged("ActivePacket");
}
}
}
// .........
}