Модераторы: gambit, Kefir, Partizan
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Биндинг данных к ListView 
V
    Опции темы
iglaweb
  Дата 24.5.2011, 10:07 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 67
Регистрация: 13.8.2009

Репутация: нет
Всего: нет



Всем добрый день!
Произвожу биндинг из бд через CollectionViewSource и BindingListCollectionView к ListView через ItemsSource, но получается так, что при начальном отображении элементы все одинаковые, а при выборе(фокусе) другого Item'а, значения всех строк меняются на выбранный Item, странно очень.

Вот C# код:
Код

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApplicationDiplom
{
    /// <summary>
    /// Interaction logic for PersonListWindow.xaml
    /// </summary>
    /// 

    public partial class PersonListWindow : Window
    {
        private CollectionViewSource MasterViewSource;
        private BindingListCollectionView MasterView;

        public PersonListWindow()
        {
            InitializeComponent();
        }

        void GetData<T>(T query)
        {
            this.MasterViewSource = (CollectionViewSource)this.FindResource("MasterView");
            this.MasterViewSource.Source = query;


            this.MasterView = (BindingListCollectionView)this.MasterViewSource.View;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ListView1.Items.Clear();
            MasterViewSource = null;
            MasterView = null;

            var q = (from p in App.db.workers
                    select new { fio = p.first_name + ' ' + p.last_name + ' ' + p.patronymic, profession = p.profession });

            GetData(q);
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
            PersonInfoWindow piw = new PersonInfoWindow();
            piw.Show();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (this.MasterView.CurrentPosition > -1)
            {
                worker s = App.db.workers.ToList()[this.MasterView.CurrentPosition];
                App.db.workers.DeleteOnSubmit(s);
                this.MasterView.RemoveAt(this.MasterView.CurrentPosition);
                App.db.SubmitChanges();
            }
        }

        private void Item_GotFocus(object sender, RoutedEventArgs e)
        {
            ListViewItem item = ((ListViewItem)(sender));
            this.ListView1.SelectedItem = item.DataContext;
            //ListView1.Items.Refresh();
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            this.MasterView.MoveCurrentToPrevious(); 
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            this.MasterView.MoveCurrentToNext(); 
        }
    }
}



А вот XAML код:
Код

<Window x:Class="WpfApplicationDiplom.PersonListWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Список сотрудников" Height="300" Width="564" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit" Loaded="Window_Loaded">
    <Window.Resources>
        <CollectionViewSource x:Key="MasterView" />
    </Window.Resources>
    <Grid>
        <ListView Name="ListView1" 
                  IsSynchronizedWithCurrentItem="True"
                  ItemsSource="{Binding Source={StaticResource MasterView}}" Margin="0,0,0,60" Grid.Row="10" SelectedIndex="-1" Grid.Column="2">
            <ListView.ItemContainerStyle>
                <Style TargetType="ListViewItem">
                    <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                    <EventSetter Event="GotFocus" Handler="Item_GotFocus" />
                </Style>
            </ListView.ItemContainerStyle>
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="ФИО" Width="120">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <Label Content="{Binding Path=fio, Source={StaticResource MasterView}}" 
                                         Margin="-6,0,-6,0"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn Header="Должность" Width="120">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <Label Content="{Binding Path=profession, Source={StaticResource MasterView}}" 
                                         Margin="-6,0,-6,0"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
        <Button Content="Удалить" Height="23" HorizontalAlignment="Left" Margin="12,226,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
        <Button Content="Добавить" Height="23" HorizontalAlignment="Left" Margin="102,226,0,0" Name="button2" VerticalAlignment="Top" Width="75" Click="button2_Click" />
        <Button Content="Назад" Height="23" HorizontalAlignment="Left" Margin="374,226,0,0" Name="button3" VerticalAlignment="Top" Width="75" Click="button3_Click" />
        <Button Content="Далее" Height="23" HorizontalAlignment="Right" Margin="0,226,12,0" Name="button4" VerticalAlignment="Top" Width="75" Click="button4_Click" />
    </Grid>
</Window>



Событие Item_GotFocus никак не влияет. Есть у меня привязка данных к комбобоксу и там вот как раз такого повторения нет и все отлично.
PM MAIL ICQ   Вверх
DenWPF
Дата 24.5.2011, 17:46 (ссылка) |    (голосов:1) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Завсегдатай
Сообщений: 1659
Регистрация: 26.9.2009

Репутация: нет
Всего: 1



Код

Content="{Binding Path=fio, Source={StaticResource MasterView}}" 

достаточно 
Код

Content="{Binding fio}"



PM MAIL   Вверх
iglaweb
Дата 24.5.2011, 18:19 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 67
Регистрация: 13.8.2009

Репутация: нет
Всего: нет



DenWPF, спасибо! все теперь правильно отображается
PM MAIL ICQ   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
1 Пользователей читают эту тему (1 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | WPF и Silverlight | Следующая тема »


 




[ Время генерации скрипта: 0.0632 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.