【发布时间】:2016-10-27 14:05:30
【问题描述】:
我在 WPF 应用程序中有两个 ListBoxes,其中包含学校课程和费用。但是,在运行时,我应该显示两个值的总和的标签只显示最近选择的值。我怎样才能使总计实际计算两个选定的值?
XAML:
<Grid>
<ListBox x:Name="courseListBox" SelectionChanged="courseListBox_SelectionChanged" HorizontalAlignment="Left" Height="126" VerticalAlignment="Top" Width="120" Margin="42,35,0,0">
<ListBoxItem>Intro to Comp Sci</ListBoxItem>
<ListBoxItem>Honors Comp Sci</ListBoxItem>
<ListBoxItem>AP Comp Sci A</ListBoxItem>
<ListBoxItem>AP Comp Sci P</ListBoxItem>
<ListBoxItem>Independent Study</ListBoxItem>
<ListBoxItem>Webpage Design</ListBoxItem>
</ListBox>
<ListBox x:Name="classListBox" SelectionChanged="classListBox_SelectionChanged" HorizontalAlignment="Left" Height="85" Margin="42,197,0,0" VerticalAlignment="Top" Width="120">
<ListBoxItem>Freshman</ListBoxItem>
<ListBoxItem>Sophomore</ListBoxItem>
<ListBoxItem>Junior</ListBoxItem>
<ListBoxItem>Senior</ListBoxItem>
</ListBox>
<Label x:Name="totalLabel" Content="25" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="168,34,0,0"/>
<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="28" VerticalAlignment="Top" Width="120" Margin="42,9,0,0"/>
<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="28" VerticalAlignment="Top" Width="120" Margin="42,169,0,0"/>
</Grid>
C#:
public partial class MainWindow : Window
{
public int courseFee = 0;
public int classFee = 0;
public int totalCost = 0;
public MainWindow()
{
InitializeComponent();
}
private void courseListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int selected = courseListBox.SelectedIndex;
if (selected == 0)
classFee = 545;
if (selected == 1)
classFee = 615;
if (selected == 2)
classFee = 1500;
if (selected == 3)
classFee = 1000;
if (selected == 4)
classFee = 2500;
if (selected == 5)
classFee = 1720;
totalCost = courseFee + classFee;
totalLabel.Content = totalCost;
}
private void classListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int selected = classListBox.SelectedIndex;
if (selected == 0)
classFee = 350;
if (selected == 1)
classFee = 275;
if (selected == 2)
classFee = 200;
if (selected == 3)
classFee = 150;
totalCost = courseFee + classFee;
totalLabel.Content = totalCost;
}
}
【问题讨论】:
-
将 courseListBox_SelectionChanged 中的“classFee”更改为“courseFee”