因此,我在使用XAML文件时遇到了一个问题;我试图使用DataGrid为用户选择的元素添加属性的表视图。我目前尝试这样做的方式是,我有一个列表,其中包含在用户单击时填充的适当对,然后将ItemsSource设置为该列表。我曾尝试更改此实现的细节(绑定ItemsSource而不引用datagrid本身,等等,但迟早它们都会遇到相同的错误)

奇怪的是(对我来说)在不同的元素上点击几下之后(当异常弹出时点击‘继续’),网格确实会填充数据,尽管它经常看起来“冻结”(在最后刷新几个元素之前显示相同的数据,没有抛出异常,但行为肯定是不一致的)
.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>发布于 2020-04-08 13:47:33
错误似乎不是来自您的数据绑定,而是来自某个xaml标记。您的GroupBox似乎没有右括号。这是一个自定义的DataGrid吗?因为它与其他控件不同,它被引用为" controls :DataGrid“。它的标记中可能有错误。
发布于 2020-04-08 19:41:08
好吧,所以我把它修好了。原来AutoGenerateColumns="true"才是罪魁祸首。我在沮丧中遇到了this thread,并尝试手动设置列,这似乎工作得很好,只需将列绑定到用于列表的类中的适当字段。
<DataGrid x:Name="dGrid"
Height="300" Margin="12"
AutoGenerateColumns="false"
ItemsSource="{Binding}"
>
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" />
<DataGridTextColumn Header="Value" Binding="{Binding Value}" />
</DataGrid.Columns>
</DataGrid>附言:我会避免选择这个作为我的答案,因为这在很大程度上是一种变通的方法,希望有更有经验的人来给出一个更全面和更简洁的解决方案(也许我以后会在这个项目中……)
https://stackoverflow.com/questions/61085862
复制相似问题