|
При загрузке данных из БД возникает исключение InvalidOperationException с сообщением: Элемент коллекции должен быть пустым перед использованием ItemsSource. Знаю, что для заполнения DataGrid можно использовать коллекции Items или ItemsSource, но одновременно их использовать нельзя: если задано значение для свойства ItemsSource и в коде C# добавляется элемент в Items, возникает исключение. |
Опубликован: 08.07.2011 | Уровень: для всех | Доступ: платный
Дополнительный материал 2:
Коды и XAML описания документов
Код класса EmployeeDomainService
[EnableClientAccess()]
public class EmployeeDomainService: LinqToEntitiesDomainService<PersonalEnterpriceEntities>
{
public IQueryable<Employee> GetEmployees()
{
return this.ObjectContext.Employees;
}
public void InsertEmployee(Employee employee)
{
if ((employee.EntityState != EntityState.Detached))
{
this.ObjectContext.ObjectStateManager.ChangeObjectState(employee,
EntityState.Added);
}
else
{
this.ObjectContext.Employees.AddObject(employee);
}
}
public void UpdateEmployee(Employee currentEmployee)
{
this.ObjectContext.Employees.AttachAsModified(currentEmployee,
this.ChangeSet.GetOriginal(currentEmployee));
}
public void DeleteEmployee(Employee employee)
{
if ((employee.EntityState == EntityState.Detached))
{
this.ObjectContext.Employees.Attach(employee);
}
this.ObjectContext.Employees.DeleteObject(employee);
}
public IQueryable<Title> GetTitles()
{
return this.ObjectContext.Titles;
}
public void InsertTitle(Title title)
{
if ((title.EntityState != EntityState.Detached))
{
this.ObjectContext.ObjectStateManager.ChangeObjectState(title,
EntityState.Added);
}
else
{
this.ObjectContext.Titles.AddObject(title);
}
}
public void UpdateTitle(Title currentTitle)
{
this.ObjectContext.Titles.AttachAsModified(currentTitle,
this.ChangeSet.GetOriginal(currentTitle));
}
public void DeleteTitle(Title title)
{
if ((title.EntityState == EntityState.Detached))
{
this.ObjectContext.Titles.Attach(title);
}
this.ObjectContext.Titles.DeleteObject(title);
}
}
}Код класса EmployeeMetadata
[MetadataTypeAttribute(typeof(Employee.EmployeeMetadata))]
public partial class Employee
{
internal sealed class EmployeeMetadata
{
private EmployeeMetadata()
{ }
public string Email { get; set; }
public Nullable<DateTime> FirstDate { get; set; }
public string FirstName { get; set; }
public short ID { get; set; }
public string Inn { get; set; }
public Nullable<DateTime> LastDate { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public byte[] Picture { get; set; }
public string Role { get; set; }
public string SecondName { get; set; }
public Title Title { get; set; }
public short TitleID { get; set; }
}
}
[MetadataTypeAttribute(typeof(Title.TitleMetadata))]
public partial class Title
{
internal sealed class TitleMetadata
{
private TitleMetadata()
{
}
public EntityCollection<Employee> Employees { get; set; }
public short ID { get; set; }
public string Title1 { get; set; }
}
}Код модифицированного класса EmployeeMetadata
internal sealed class EmployeeMetadata
{
private EmployeeMetadata()
{ }
[Display(Name = "Эл. почта", Order = 7)]
public string Email { get; set; }
[Display(Name = "Дата приема", Order = 9)]
public Nullable<DateTime> FirstDate { get; set; }
[Display(Name = "Имя", Order = 2)]
public string FirstName { get; set; }
public short ID { get; set; }
[Display(Name = "ИНН", Order = 6)]
public string Inn { get; set; }
[Display(Name = "Дата увольнения", Order = 10)]
public Nullable<DateTime> LastDate { get; set; }
[Display(Name = "Фамилия", Order = 1)]
public string LastName { get; set; }
[Display(Name = "Телефон", Order = 8)]
public string Phone { get; set; }
[Display(Name = "Фото", Order = 0)]
public byte[] Picture { get; set; }
[Display(Name = "Роль", Order = 5)]
public string Role { get; set; }
[Display(Name = "Отчество", Order = 3)]
public string SecondName { get; set; }
[Display(Name = "Должность", Order = 4)]
[Include]
EntityCollection<Title> Title { get; set; }
public short TitleID { get; set; }
}XAML-описание сетки gridSearch фрагмента страницы EmployeePage
<Border x:Name="borderSearch" Grid.Row="0" Grid.Column="1"
CornerRadius="10" Margin="5" Background="#FFF2F2F2" BorderThickness="1">
<Grid x:Name="gridSearch" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions >
<RowDefinition Height="30" />
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.ColumnSpan="2" Text="Поиск"
Margin="2" HorizontalAlignment="Center"/>
<TextBlock Grid.Row="1" Text="По фамилии"
HorizontalAlignment="Right" Margin="10,2,10,2" VerticalAlignment="Center"/>
<TextBlock Grid.Row="2" Text="По должности" HorizontalAlignment="Right"
Margin="10,2,10,2" VerticalAlignment="Center"/>
<TextBox x:Name="textBoxLastName" Grid.Column="1" Grid.Row="1" Height="23"
HorizontalAlignment="Left" Margin="20,2,20,0"
VerticalAlignment="Top" Width="300"
TextChanged ="textBoxLastName_TextChanged" />
<input:AutoCompleteBox Grid.Row="2" Grid.Column="1" Name="FilterText"
HorizontalAlignment="Left"
ValueMemberBinding="{Binding Title}"
ItemsSource="{Binding ElementName=titleEmployeeDomainDataSource,
Path=Data}"
TextChanged ="FilterText_TextChanged"
Margin="20,2,20,2" Height="23" Width="300"/>
</Grid>
</Border>Код класса EmployeeMetadata с атрибутами для валидации
internal sealed class EmployeeMetadata
{
private EmployeeMetadata()
{ }
[Display(Name = "Эл. почта", Order = 7)]
[RegularExpression("^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|" +
" (([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$",
ErrorMessageResourceName = "ValidationErrorInvalidEmail",
ErrorMessageResourceType = typeof(ValidationErrorResources))]
public string Email { get; set; }
[Display(Name = "Дата приема", Order = 9)]
public Nullable<DateTime> FirstDate { get; set; }
[Display(Name = "Имя", Order = 2)]
[RegularExpression((@"^[А-Яа-я' ''-']{1,20}$"),
ErrorMessage = "Недопустимые символы или более 20 символов")]
[Required(ErrorMessage = "Поле обязательно должно быть заполнено")]
public string FirstName { get; set; }
[Editable(false)]
public short ID { get; set; }
[Display(Name = "ИНН", Order = 6)]
[RegularExpression((@"^[0-9]{1,12}$"),
ErrorMessage = "Допустимы толька цифровые символы,
длина ИНН - 12 символов")]
[CustomValidation(typeof(ValidaterInn), "ValidateInn")]
public string Inn { get; set; }
[Display(Name = "Дата увольнения", Order = 10)]
public Nullable<DateTime> LastDate { get; set; }
[Display(Name = "Фамилия", Order = 1)]
[Required(ErrorMessage = "Поле обязательно должно быть заполнено")]
[RegularExpression((@"^[А-Яа-я' ''-']{1,20}$"),
ErrorMessage = "Недопустимые символы или более 20 символов")]
public string LastName { get; set; }
[Display(Name = "Телефон", Order = 8)]
public string Phone { get; set; }
[Display(Name = "Фото", Order = 0)]
public byte[] Picture { get; set; }
[Display(Name = "Роль", Order = 5)]
[RegularExpression((@"^[А-Яа-я' ''-']{1,20}$"),
ErrorMessage = "Недопустимые символы или более 20 символов")]
public string Role { get; set; }
[Display(Name = "Отчество", Order = 3)]
[RegularExpression((@"^[А-Яа-я' ''-']{1,20}$"),
ErrorMessage = "Недопустимые символы или более 20 символов")]
[Required(ErrorMessage = "Поле обязательно должно быть заполнено")]
public string SecondName { get; set; }
[Include]
[Display(Name = "Должность", Order = 4)]
public EntityCollection<Title> Title { get; set; }
public short TitleID { get; set; }
}