//In Test.xaml
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition Height="30"></RowDefinition>
</Grid.RowDefinitions>
<DataGrid Grid.Row="0" AutoGenerateColumns="False" ItemsSource="{Binding}" Name="dtGridTran" HorizontalAlignment="Left" CanUserAddRows="True" >
<DataGrid.Columns>
<DataGridTextColumn Header="X" Binding="{Binding Path=X, UpdateSourceTrigger=PropertyChanged}" Width="200"/>
<DataGridTextColumn Header="Y" Binding="{Binding Path=Y, UpdateSourceTrigger=PropertyChanged}" Width="200" />
</DataGrid.Columns>
</DataGrid>
<Label Grid.Row="1" Content=" Total Sum of x and Y">
</Label>
<TextBox Grid.Row="1" Text="{Binding Path=Total, UpdateSourceTrigger=PropertyChanged}" Margin="150,0,0,0" Width="100"></TextBox>
</Grid>
//In Test.xaml.cs file
public partial class Test : Page
{
Derivedclass D = new Derivedclass();
public Test()
{
InitializeComponent();
this.DataContext = D;
dtGridTran.ItemsSource = new TestGridItems();
}
}
public class TestGridItems : List<Derivedclass>
{
}
// In Base class
public class Baseclass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private int mTotal = 0;
private int mID = 0;
public int Total
{
get { return mTotal; }
set
{
mTotal = value; OnPropertyChanged("Total");
}
}
public int ID
{
get { return mID; }
set { mID = value; }
}
public string Item = "xxx";
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string PropertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(PropertyName));
}
}
}
In Derivedclass.cs
public class Derivedclass : Baseclass, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private int mX = 0;
private int mY = 0;
public int X
{
get { return mX; }
set
{
mX = value;
base.Total = base.Total + mX;
OnPropertyChanged("Total");
}
}
public int Y
{
get { return mY; }
set
{
mY = value;
base.Total = base.Total + mY;
OnPropertyChanged("Total");
}
}
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string PropertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(PropertyName));
}
}
}
}
ここでは、x 値と y 値の合計を見つけようとしています。しかし、m は合計ゼロを取得します。合計プロパティは基本クラスにあります。テキストボックスに表示したい x 列と y 列の合計が必要ですが、複数の値を追加している間、ベースクラスの Total プロパティはゼロを返します。