Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > WPF и Silverlight > Не получается DataBinding с ListView


Автор: dAlex 13.12.2010, 14:15
Пытаюсь сделать DataBinding с ListView

Код

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        ObservableCollection<StrikeData> _StrikeCollection =  new ObservableCollection<StrikeData>();

        public MainWindow()
        {
            InitializeComponent();
        }

        public ObservableCollection<StrikeData> StrikeCollection
        { get { return _StrikeCollection; } }

        public class StrikeData
        {
            public int Strike { get; set; }
            public int LimToEndOfDayBuy { get; set; }
            public int LimToEndOfDaySell { get; set; }
            public int LimToEndOfSessionBuy { get; set; }
            public int LimToEndOfSessionSell { get; set; }
            public int PosBuy { get; set; }
            public int PosSell { get; set; }
        }


        private void button1_Click(object sender, RoutedEventArgs e)
        {
            _StrikeCollection.Add(new StrikeData
            {
                LimToEndOfDayBuy = int.Parse(textBox1.Text),
                LimToEndOfDaySell = 0,
                LimToEndOfSessionBuy = 0,
                LimToEndOfSessionSell = 0,
                PosBuy = 0,
                PosSell = 0
            });          
        }

    
    }
}


Код

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="639">
    <Grid>
        <TextBox HorizontalAlignment="Left" Margin="12,24,0,264" Name="textBox1" Width="120" />
        <Button Content="Add" Height="23" HorizontalAlignment="Left" Margin="36,53,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
        <ListView Height="287" HorizontalAlignment="Left" Margin="150,12,0,0" Name="listView1" VerticalAlignment="Top" Width="440" ItemsSource="{Binding StrikeCollection}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Width="70" Header="Страйки" DisplayMemberBinding="{Binding Strike}"/>
                    <GridViewColumn Width="50" Header="Продать" DisplayMemberBinding="{Binding LimToEndOfDaySell}"/>
                    <GridViewColumn Width="50" Header="Купить" DisplayMemberBinding="{Binding LimToEndOfDayBuy}"/>
                    <GridViewColumn Width="50" Header="Продать" DisplayMemberBinding="{Binding LimToEndOfSessionSell}"/>
                    <GridViewColumn Width="50" Header="Купить" DisplayMemberBinding="{Binding LimToEndOfSessionBuy}"/>
                    <GridViewColumn Width="50" Header="Продать" DisplayMemberBinding="{Binding PosSell}"/>
                    <GridViewColumn Width="50" Header="Купить" DisplayMemberBinding="{Binding PosBuy}"/>
                </GridView>
               </ListView.View>
        </ListView>
    </Grid>
</Window>


При добавлении объекта в Collection он появляется, все в порядке, но ListFiew на форме не обновляется. Может, напутала где-то с именами, не знаю. Только пробую WPF, подскажите, пожалуйста, где копать =)

Автор: Kaerus 13.12.2010, 17:39
биндинг не работает (источник не находиться), поправь
Код

public MainWindow()
{
    InitializeComponent();
    DataContext = this;
}

Автор: dAlex 14.12.2010, 10:17
Kaerus, огромное спасибо, заработало =)

Автор: dAlex 15.12.2010, 15:27
хм, вылез глюк.
При обновлении одного поля элемента из коллекции, на форме он не меняется. То есть в коллекции изменение произошло, а на форме - нет. От чего это может быть?

Добавлено через 13 минут и 30 секунд
Исправила, использовав INotifyChanged

Теперь класс выглядит так
Код

public class StrikeData:INotifyPropertyChanged
        {
            private int _Strike;
            public int Strike 
            { 
                get {return _Strike;} 
                set
                {
                     _Strike = value;
                     NotifyPropertyChanged("Strike");
                }
            }

            private int _LimToEndOfDayBuy;
            public int LimToEndOfDayBuy 
            { 
                get {return _LimToEndOfDayBuy;} 
                set
                {
                     _LimToEndOfDayBuy = value;
                     NotifyPropertyChanged("LimToEndOfDayBuy");
                }
            }

            private int _LimToEndOfDaySell;
            public int LimToEndOfDaySell 
            { 
                get {return _LimToEndOfDaySell;} 
                set
                {
                     _LimToEndOfDaySell = value;
                     NotifyPropertyChanged("LimToEndOfDaySell");
                }
            }

            private int _LimToEndOfSessionBuy;
            public int LimToEndOfSessionBuy 
            { 
                get {return _LimToEndOfSessionBuy;} 
                set
                {
                     _LimToEndOfSessionBuy = value;
                     NotifyPropertyChanged("LimToEndOfSessionBuy");
                }
            }

            private int _LimToEndOfSessionSell;
            public int LimToEndOfSessionSell 
            { 
                get {return _LimToEndOfSessionSell;} 
                set
                {
                     _LimToEndOfSessionSell = value;
                     NotifyPropertyChanged("LimToEndOfSessionSell");
                }
            }

            private int _PosBuy;
            public int PosBuy 
            { 
                get {return _PosBuy;} 
                set
                {
                     _PosBuy = value;
                     NotifyPropertyChanged("PosBuy");
                }
            }

            private int _PosSell;
            public int PosSell 
            { 
                get {return _PosSell;}
                set
                {
                     _PosSell = value;
                     NotifyPropertyChanged("PosSell");
                }
            }     

            private PropertyChangedEventHandler _propertyChanged;

            event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
            {
                add { _propertyChanged += value; }
                remove { _propertyChanged -= value; }
            }
            private void NotifyPropertyChanged(string info)
            {
                if (_propertyChanged != null)
                    _propertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }



вместо
Код

public class StrikeData
        {
            public int LimToEndOfDayBuy { get; set; }
            public int LimToEndOfDaySell { get; set; }
            public int LimToEndOfSessionBuy { get; set; }
            public int LimToEndOfSessionSell { get; set; }
            public int PosBuy { get; set; }
            public int PosSell { get; set; }
}
             

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)