나는 ObservableCollection
이고 Students
입니다. 각 학생에게는 Grade 속성이 있습니다. 단추를 누르거나 타이머를 만들지 않고도 모든 학생의 AverageGrade
속성을 사용하고 싶습니다. 이 읽기 전용 AverageGrade
속성에 DependencyProperty
을 어떻게 사용합니까? 당신이 정상 VM 속성 걸릴처럼 보일 것을 위해 DP를 원하는 이유이에 대해 DependencyProperty를 사용할 수 있습니까?
Student.cs
using System.ComponentModel;
using System.Windows;
using System;
namespace WpfApplication17.Models
{
class Student : INotifyPropertyChanged
{
#region Constructors
public Student(string firstName, string lastName, double grade)
{
this.FirstName = firstName;
this.LastName = lastName;
this.Grade = grade;
}
#endregion
#region Properties
private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
OnPropertyChanged("FirstName");
}
}
private string _lastName;
public string LastName
{
get { return _lastName; }
set
{
_lastName = value;
OnPropertyChanged("LastName");
}
}
private double _grade;
public double Grade
{
get { return _grade; }
set
{
_grade = value;
OnPropertyChanged("Grade");
}
}
#endregion
#region PropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}
MainWindowViewModel
using WpfApplication17.ViewModel;
using System.Collections.ObjectModel;
using WpfApplication17.Models;
namespace WpfApplication17.ViewModels
{
class MainWindowViewModel : ViewModelBase
{
#region Constructors
public MainWindowViewModel()
{
Students = new ObservableCollection<Student>();
Students.Add(new Student("Frank", "Sinatra", 7));
Students.Add(new Student("Bart", "Simpson", 6));
}
#endregion
#region Properties
private ObservableCollection<Student> _students;
public ObservableCollection<Student> Students
{
get { return _students; }
set
{
_students = value;
OnPropertyChanged("Students");
}
}
public double AverageGrade
{
get { return GetAverageGrade(); }
}
public double GetAverageGrade()
{
double sum = 0;
foreach (Student s in Students)
sum += s.Grade;
return sum/(double)Students.Count;
}
#endregion
}
}
MainWindow.xaml
<Window x:Class="WpfApplication17.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel Orientation="Horizontal">
<DataGrid ItemsSource="{Binding Students}" />
<Label Content="Average Grade:" />
<Label Content="{Binding AverageGrade}" />
</StackPanel>
</Window>
당신의 코드를 부착하지 마십시오. 귀하의 질문에 답하십시오. –
그리고 quetion과 관련된 코드 만 포함시켜야합니다! – GameScripting
죄송합니다, 코드가 추가되었습니다. – Pizzaguru