WPF:System.ArgumentException => {"'{0}'不是Visual或Visual3D."}

msf*_*boy 6 wpf listbox exception datagridtemplatecolumn

当我双击 - 或者当它已经聚焦时单击一次 - 在我的DataGridTemplateColumn中的Listbox的空白区域中的项目下面时,我得到上面的错误消息.

我错了什么?

这是我的代码:

<DataGridTemplateColumn Width="0.3*" Header="Attachments">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <StackPanel Orientation="Vertical">
                <Button>Add</Button>
                <Button>Delete</Button>
                <ListBox Name="itemListBox" BorderThickness="0" ItemsSource="{Binding Attachments}" >                                   
                    <ListBox.ItemTemplate>
                        <DataTemplate>                                           
                            <StackPanel Orientation="Vertical" Margin="5">                                                
                                <TextBlock Text="{Binding DocumentFilename}" />
                            </StackPanel>                                            
                        </DataTemplate>
                    </ListBox.ItemTemplate>                                     
                </ListBox>
            </StackPanel>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn> 
Run Code Online (Sandbox Code Playgroud)

关于我点击"myPhotos.png"项目条目下方的图片: alt text http://666kb.com/i/bh6lbd47okwancfel.png

编辑:这个错误也已经在XAML中通过工具提示可见,只是没有看到错误工具提示......

Jos*_*osh 9

这确实是一个错误.我运行你的repro项目并在抛出异常时检出调用堆栈.它在调用VisualTreeHelper.IsAncestorOf期间发生在DataGridCell.RemoveBindingExpressions中.后一种方法在传递非Visual或Visual3D的对象时抛出异常.但DataGridCell正在传递它,无论绑定的目标是什么元素.在你的情况下恰好是一个不是从Visual派生的Run.

我想你可以通过使用IValueConverter来创建FlowDocument并绑定RichTextBox.Document以便将绑定应用于RichTextBox来解决它.但由于Document不是依赖属性,因此它不能成为绑定的目标.

因此,您可能想要做的是创建一个托管RichTextBox控件的UserControl:

<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <Local:HomeworkControl Text="{Binding Homework}" />
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>
Run Code Online (Sandbox Code Playgroud)

然后在该用户控件中,您将负责构建RichTextBox,文档,运行等.不幸的是,我认为这只是DataGrid控件中的限制(也就是bug).


She*_*kel 6

有趣的是,这也发生在我身上.乔什说的话让我思考.看起来,一旦你选择了单元格并再次选择它,它会尝试加载我的情况下未指定的CellEditingTemplate和你的,它会抛出Visual/Visual3d异常.

我通过在DataGridTemplateColumn上指定IsReadOnly ="True"来修复它.我还是不使用CellEditingTemplate,因为我正在使用加载在单元格模板中的TextBoxes/DatePicker/Checkbox等进行批量插入.