wpf - 设置 DataGrid ItemsSource 会导致 XamlParseException
问题描述
所以我使用的 XAML 文件有问题;我正在尝试使用 DataGrid 为用户选择的元素添加属性的表格视图。我目前尝试这样做的方式是,我有一个列表,其中包含在用户单击时填充的适当对,然后将 ItemsSource 设置为该列表。我尝试更改此实现的细节(绑定 ItemsSource 而不引用数据网格本身等,但迟早它们似乎都会遇到相同的错误)
奇怪的事情(对我来说)是,在不同的元素上点击几下(并在弹出异常时点击“继续”),网格确实填充了数据,尽管它通常似乎“冻结”(显示相同的数据)在最后刷新几个元素之前的几个元素,没有抛出异常,但行为肯定不一致)
.xaml.cs
// ParameterPair is a custom class that contains 2 string fields (name, value)
public List<ParameterPair> AllParameters { get; private set; } = new List<ParameterPair>();
// called (only) when a new element is click
// ... code to populate AllParameters here
// definitely populates properly, checked through debugging
this.dGrid.ItemsSource = AllParameters;
.xaml
<Page ...>
<Grid HorizontalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TabControl>
<TabItem Header="Add Constraint">
<Grid Name="loginBlock" Grid.Row="0">
<GroupBox Header="Properties"
HorizontalAlignment="Stretch"
VerticalAlignment="Top"
Margin="10, 10, 10, 0">
<StackPanel>
<controls:DataGrid x:Name="dGrid"
Height="300" Margin="12"
AutoGenerateColumns="true"
ItemsSource="{Binding}"
/>
</StackPanel>
</GroupBox>
</Grid>
</TabItem>
<TabItem Header="Manage Constraints" />
</TabControl>
</Grid>
</Page>
解决方案
该错误似乎不是来自您的数据绑定,而是来自某处的 xaml 标记。您的 GroupBox 似乎没有右括号。这是一个自定义的 DataGrid 吗?因为它与您的其他控件不同,它被称为“控件:DataGrid”。它的标记可能有问题。