XamlParseException, установить connectionId выдал исключение - PullRequest
1 голос
/ 21 сентября 2019

Когда я запускаю ниже Xaml, я получаю ошибку:

System.Windows.Markup.XamlParseException: '' Установить connectionId вызвало исключение. 'Номер строки '18' и позиция строки '14'. '

Внутреннее исключение 1: InvalidCastException: невозможно преобразовать объект' System.Windows.Style 'в тип' System.Windows.Controls.TreeView '.

Пожалуйста, не отмечайте этот вопрос как дубликат, потому что я проверил все подобные вопросы в SO и не смог найти работающий ответ.

<Window x:Class="WpfApp1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp1"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Window.Resources>

    <DataTemplate x:Key="xxx">
        <Grid>
            <local:ButtonEx ToolTipService.ToolTipClosing="ButtonEx_ToolTipClosing"/>
        </Grid>
    </DataTemplate>

    <Style x:Key="TreeViewItemStyle" TargetType="TreeViewItem" >
        <EventSetter Event="MouseDoubleClick" Handler="TreeViewItem_MouseDoubleClick"/>
    </Style>

</Window.Resources>
<Grid>
    <TreeView x:Name="treeViewBookmarks" ItemContainerStyle="{StaticResource TreeViewItemStyle}"/>
</Grid>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void ButtonEx_ToolTipClosing(object sender, ToolTipEventArgs e)
    {
    }

    private void TreeViewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
    }
}

class ButtonEx : Button
{
}

Если я удаляю: ToolTipService.ToolTipClosing="ButtonEx_ToolTipClosing", или удаляю: EventSetter Event="MouseDoubleClick" Handler="TreeViewItem_MouseDoubleClick", или удаляю x:Name="treeViewBookmarks" - без ошибок.

Если я использую Button вместо ButtonEx - без ошибок.

1 Ответ

1 голос
/ 21 сентября 2019

Хороший вопрос.

Похоже, что это ошибка в компоненте WPF PresentationBuildTasks.

Как вы знаете, создание проекта WPF вызывает много сгенерированных компиляторомкод для внедрения в ваши UI-классы.

Например, ваш MainWindow класс дополнительно получит что-то вроде этого:

[DebuggerNonUserCode]
[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent()
{
    if (!_contentLoaded)
    {
        _contentLoaded = true;
        Uri resourceLocater = new Uri("/WpfApp1;component/mainwindow.xaml", UriKind.Relative);
        Application.LoadComponent(this, resourceLocater);
    }
}

[DebuggerNonUserCode]
[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
[EditorBrowsable(EditorBrowsableState.Never)]
void IComponentConnector.Connect(int connectionId, object target)
{
    if (connectionId == 2)
    {
        treeViewBookmarks = (TreeView)target;
    }
    else
    {
        _contentLoaded = true;
    }
}

[DebuggerNonUserCode]
[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
[EditorBrowsable(EditorBrowsableState.Never)]
void IStyleConnector.Connect(int connectionId, object target)
{
    if (connectionId == 1)
    {
        EventSetter eventSetter = new EventSetter();
        eventSetter.Event = Control.MouseDoubleClickEvent;
        eventSetter.Handler = new MouseButtonEventHandler(TreeViewItem_MouseDoubleClick);
        ((Style)target).Setters.Add(eventSetter);
    }
}

Эти Connect методы генерируются неправильно.

Если вы замените ButtonEx в DataTemplate на Button, эти Connect методы будут выглядеть следующим образом:

[DebuggerNonUserCode]
[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
[EditorBrowsable(EditorBrowsableState.Never)]
void IComponentConnector.Connect(int connectionId, object target)
{
    if (connectionId == 3)
    {
        treeViewBookmarks = (TreeView)target;
    }
    else
    {
        _contentLoaded = true;
    }
}

[DebuggerNonUserCode]
[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
[EditorBrowsable(EditorBrowsableState.Never)]
void IStyleConnector.Connect(int connectionId, object target)
{
    switch (connectionId)
    {
    case 1:
        ((Button)target).AddHandler(ToolTipService.ToolTipClosingEvent, new ToolTipEventHandler(ButtonEx_ToolTipClosing));
        break;
    case 2:
    {
        EventSetter eventSetter = new EventSetter();
        eventSetter.Event = Control.MouseDoubleClickEvent;
        eventSetter.Handler = new MouseButtonEventHandler(TreeViewItem_MouseDoubleClick);
        ((Style)target).Setters.Add(eventSetter);
        break;
    }
    }
}

Смотрите, connectionId отличается.

Вам следует сообщить об этой проблеме в Microsoft.Что-то идет не так в PresentationBuildTasks для вашего случая.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...