Здравствуйте. В общем, есть главное окно, DataContext которого:
XML |
1
2
| DataContext="{Binding Source={StaticResource Locator},
Path=Main}" |
|
В нём же DataGrid:
XML |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| <DataGrid x:Name="appsDataGrid"
Margin="1,0"
AutoGenerateColumns="False"
DataContext="{Binding Source={StaticResource Locator}, Path=ApplicationsEditor}"
ItemsSource="{Binding Path=RootElements}"
SelectedIndex="{Binding Source={StaticResource Locator},
Path=ApplicationsEditor.ElementsSelectedIndex,
Mode=TwoWay}"
SelectionMode="Single"
Style="{StaticResource DataGridStyle}">
<DataGridTextColumn x:Name="AppNumberColumn"
Binding="{Binding Path=Id}"
ClipboardContentBinding="{x:Null}"
Header="№ Заявки" />
<DataGridTextColumn x:Name="StatusColumn"
Binding="{Binding IsCompleted}"
ClipboardContentBinding="{x:Null}"
Header="Выполнено" />
</DataGrid> |
|
При попытке скомпилировать проект вылетает исключение:
Первый этап обработки исключения типа "System.Windows.Markup.XamlParseException" в PresentationFramework.dll
Дополнительные сведения: "Добавление значения в коллекцию типа "System.Windows.Controls.ItemCollection" вызвало исключение.": номер строки "134" и позиция в строке "33".
Так вот. Я создал тестовый проект и в нём всё нормально работает, а в основном нет. Может подскажете, что это может быть?
C# |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
| using GalaSoft.MvvmLight;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Client.ViewModels
{
/// <summary>
/// Позволяет создать поддержку удаления элементов из списка в связанном элементе управления (DataGrid, например)
/// с выбором предыдущего элемента в списке (чтобы в списке всегда было что-то выбрано). Так же позволяет
/// создать поддержку подсчёта ширины всех колонок в связанном элементе управления.
/// </summary>
public abstract class CollectionSupportedWorkspace<T> : ViewModelBase
{
public event EventHandler CloseRequested;
private int _lastElementsSelectedIndex;
private int _elementsSelectedIndex;
private double _actualWidthOfAllColumns;
private string _title;
private bool _isPopupEnabled;
protected readonly List<T> elementsForRemoving;
protected CollectionSupportedWorkspace()
{
IsPopupEnabled = true;
_elementsSelectedIndex = -1;
_lastElementsSelectedIndex = -1;
elementsForRemoving = new List<T>();
RootElements = new ObservableCollection<T>();
}
protected virtual void OnCloseRequest()
{
EventHandler handler = CloseRequested;
if (handler != null) handler(this, EventArgs.Empty);
}
/// <summary>Текущий индекс выбранного элемента в связанном списке</summary>
public int ElementsSelectedIndex
{
get { return _elementsSelectedIndex; }
set
{
LastElementsSelectedIndex = _elementsSelectedIndex;
_elementsSelectedIndex = value;
RaisePropertyChanged("ElementsSelectedIndex");
}
}
/// <summary>Предыдущий индекс выбранного элемента в связанном списке</summary>
public int LastElementsSelectedIndex
{
get { return _lastElementsSelectedIndex; }
set
{
_lastElementsSelectedIndex = value;
RaisePropertyChanged("LastElementsSelectedIndex");
}
}
/// <summary>Ширина всех колонок в связанном элементе управления (DataGrid, например)</summary>
public double ActualWidthOfAllColumns
{
get { return _actualWidthOfAllColumns; }
set
{
_actualWidthOfAllColumns = value;
RaisePropertyChanged("ActualWidthOfAllColumns");
}
}
/// <summary>Заголовок окна</summary>
public string Title
{
get { return _title; }
set
{
_title = value;
RaisePropertyChanged("Title");
}
}
/// <summary>Задаёт показывать ли Popup при наведении курсора на DataGridRow</summary>
public bool IsPopupEnabled
{
get { return _isPopupEnabled; }
set
{
_isPopupEnabled = value;
RaisePropertyChanged("IsPopupEnabled");
}
}
protected void RecountSelectedIndex()
{
if (LastElementsSelectedIndex > -1 && RootElements.Count > LastElementsSelectedIndex)
{
ElementsSelectedIndex = LastElementsSelectedIndex;
}
else if (LastElementsSelectedIndex > 0 && RootElements.Count > 0)
{
ElementsSelectedIndex = LastElementsSelectedIndex - 1;
}
}
/// <summary>
/// Содержит основные данные, отображаемые в списке
/// </summary>
public ObservableCollection<T> RootElements { get; protected set; }
/// <summary>
/// Создать новый или клонировать основной элемент, отображаемый в списке
/// </summary>
/// <param name="element">Элемент, с которого будет клонирован новый объект, или если передан null, то создан новый</param>
/// <returns></returns>
public abstract T CloneIfNotNullOrCreateNewRootElement(T element);
}
} |
|
C# |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
| using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BSU.API.Data;
using Client.Settings;
using Server.Database;
namespace Client.ViewModels.Applications
{
public class L1ApplicationEditorViewModel : CollectionSupportedWorkspace<L1ApplicationViewModel>
{
private L1ApplicationViewModel _selectedApplication;
private DetailedProperty<string, string> _detailedProperty;
public L1ApplicationEditorViewModel()
{
SelectedAppDetails = new ObservableCollection<DetailedProperty<string, string>>();
var apps = Database.Instance.GetApplications(Constants.LineNumber);
ApplicationsToCollectionAsViewModel(apps);
}
private void ApplicationsToCollectionAsViewModel(IEnumerable<Application> applications)
{
RootElements.Clear();
foreach (Application app in applications)
{
RootElements.Add(new L1ApplicationViewModel(app));
}
}
public L1ApplicationViewModel SelectedApplication
{
get { return _selectedApplication; }
set
{
_selectedApplication = value;
SelectedAppDetails.Clear();
//SelectedAppDetails.Add(new DetailedProperty<string, string>());
RaisePropertyChanged("SelectedApplication");
}
}
public DetailedProperty<string, string> DetailedObject
{
get { return _detailedProperty; }
set
{
_detailedProperty = value;
RaisePropertyChanged("DetailedObject");
}
}
public ObservableCollection<DetailedProperty<string, string>> SelectedAppDetails { get; protected set; }
public override L1ApplicationViewModel CloneIfNotNullOrCreateNewRootElement(L1ApplicationViewModel element)
{
throw new NotImplementedException();
}
}
} |
|
В других ViewModel я наследую CollectionSupportedWorkspace<T> и всё нормально работает (на всякий случай упомянул).
Кстати, вот ещё скрин, на котором видно, что колонки не видят объект коллекции, к которому я их биндю: