Привязка данных из ObservableCollection <User>к странице xaml - PullRequest
1 голос
/ 18 апреля 2011

я пытаюсь привязать данные из ObservableCollection к странице xaml Пожалуйста, дайте мне знать, как достичь этого

Страница XAML

<UserControl.Resources>
        <DataTemplate x:Key="User" >
        </DataTemplate>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot" DataContext="{Binding Source={StaticResource User}}">

        <data:DataGrid AutoGenerateColumns="True" 
               HeadersVisibility="All"
               ItemsSource="{Binding }"                       
               RowBackground="Cornsilk" 
               AlternatingRowBackground="BlanchedAlmond"
               ColumnWidth="85" RowHeight="30"
               IsReadOnly="True" CanUserResizeColumns="False">
        </data:DataGrid>
    </Grid>

.cs page

    ObservableCollection<User> users;
        public SLObservableCollectionSample()
        {
            InitializeComponent();
            users = getUserCollection();
    }

ObservableCollection<User> getUserCollection()
        {
            ObservableCollection<User> rVal = new ObservableCollection<User>();

            rVal.Add(new User { Name = "Tom", Score = 2 });
            rVal.Add(new User { Name = "Sam", Score = 3 });
            rVal.Add(new User { Name = "John", Score = 4 });
            rVal.Add(new User { Name = "Dave", Score = 5 });
            rVal.Add(new User { Name = "Sue", Score = 1 });
            return rVal;
        }

 #region User INotifyPropertyChanged
        public class User : INotifyPropertyChanged
        {
            private string name;

            public string Name
            {
                get { return name; }
                set
                {
                    if (value != name)
                    {
                        name = value;
                        onPropertyChanged(this, "Name");
                    }
                }
            }

            private long score;

            public long Score
            {
                get { return score; }
                set
                {
                    if (score != value)
                    {
                        score = value;
                        onPropertyChanged(this, "Score");
                    }
                }
            }

            #region INotifyPropertyChanged Members

            public event PropertyChangedEventHandler PropertyChanged;

            private void onPropertyChanged(object sender, string propertyName)
            {

                if (this.PropertyChanged != null)
                {
                    PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
                }
            }

            #endregion

        #endregion

Спасибо

Prince

...