Ошибка «Недопустимая разметка» в Visual Studio 2017 Designer, хотя код работает - PullRequest
0 голосов
/ 14 февраля 2019

Я скопировал проект, сделанный в этом видео на Youtube: https://www.youtube.com/watch?v=6OwyNiLPDNw&t=3602s

Тем не менее, дизайнер показывает «Неверная разметка», хотя код работает отлично и сборка успешна.(Парень в Youtube-видео сталкивается с той же проблемой (в 59: 43-59: 56), но каким-то образом решает ее. У меня все та же проблема.)

XAML выделяет синим подчеркиванием под: Source =«{Binding, который показывает ошибку: имя« HeaderToImageConverter »не существует в пространстве имен« clr-namespace: WpfTreeView ». Программа по-прежнему работает нормально, я просто не вижу конструктора.

У меня естьпопытался решить эту проблему, выполнив следующие действия:

  1. Конфигурирование между платформами Debug / Release и x64 / x84
  2. Удаление папок .bin .obj и .vs
  3. Удалить папку ShadowCache
  4. Очистить, перестроить и построить решение несколько раз
  5. Сбросить настройки Visual Studio и перезагрузить компьютер

XAML:

<Window x:Class="WpfTreeView.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:WpfTreeView"
        Loaded="Window_Loaded"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>

        <TreeView x:Name="FolderView">
            <TreeView.Resources>

                <Style TargetType="{x:Type TreeViewItem}">
                    <Setter Property="HeaderTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">
                                    <Image Width="20" Margin="3" 
                                        Source="{Binding
                                            RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}},
                                            Path=Tag,
                                            Converter={x:Static local:HeaderToImageConverter.Instance}}" />
                                    <TextBlock VerticalAlignment="Center" Text="{Binding}" />
                                </StackPanel>
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </TreeView.Resources>
        </TreeView>
    </Grid>
</Window>

C # (класс HeaderToImageConverter):

using System;
using System.Globalization;
using System.IO;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace WpfTreeView
{
    /// <summary>
    /// Converts a full path to a specific image type of a drive, folder or file
    /// </summary>
    [ValueConversion(typeof(string), targetType: typeof(BitmapImage))]
    public class HeaderToImageConverter : IValueConverter
    {
        public static HeaderToImageConverter Instance = new HeaderToImageConverter();

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // Get the full path
            var path = (string)value;

            // If the path is null, ignore
            if (path == null)
                return null;

            // Get the name of the file/folder
            var name = MainWindow.GetFileFolderName(path);

            // By default, we presume an image
            var image = "Images/Checkmark.png";

            // If the name is blank, we presume it's a drive as we cannot have a blank file or folder name
            if (string.IsNullOrEmpty(name))
                image = "Images/Arrow.png";
            else if (new FileInfo(path).Attributes.HasFlag(FileAttributes.Directory))
                image = "Images/Checkmark.png";

            return new BitmapImage(new Uri($"pack://application:,,,/{image}"));
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

1 Ответ

0 голосов
/ 14 февраля 2019

Лично я считаю Converter={x:Static local:HeaderToImageConverter.Instance}}" /> странным способом обращения к конвертеру.Вы также можете добавить конвертер в ваш app.xaml, например

<Application x:Class="WpfTreeView.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:wpftreeview="clr-namespace:WpfTreeView"
         StartupUri="MainWindow.xaml">
<Application.Resources>
    <ResourceDictionary>


        <wpftreeview:HeaderToImageConverter  
            x:Key="HeaderToImageConverter "/>

    </ResourceDictionary>
</Application.Resources>

Далее, назовите свой конвертер с помощью

Source="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}}, Path=Tag, Converter={StaticResource HeaderToImageConverter}}" />

Редактировать:

Можете ли вы попробовать добавить сборку в объявление пространства имен?xmlns:local="clr-namespace:WpfTreeView;assembly=MyAssembly

...