//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 属性返回零。