我在WPF中有一个 ListBox 。在这个ListBox中,我有一个标签,我需要命名为labelLessonAmount。
我有这段代码:
foreach (Course c in items)
{
var lessons = context.Lessons.Where(l => l.CourseId == c.CourseId).Count();
}
现在我想将来自Count()
的金额放入ListBox中的标签中。但我无法达到标签。我怎样才能做到这一点?我知道有一些具有约束力但却看不到我如何在标签中得到这个......
<ListBox x:Name="listBoxLessons" Margin="10,47,10,10" VerticalContentAlignment="Top" HorizontalContentAlignment="Stretch" Background="{x:Null}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" BorderBrush="#00ABADB3" VerticalAlignment="Top">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="4"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid DockPanel.Dock="Top" Height="200" MaxHeight="200">
<Grid.RowDefinitions>
<RowDefinition Height="10*" MaxHeight="50"/>
<RowDefinition Height="30*" MaxHeight="60"/>
<RowDefinition Height="30*" MaxHeight="20"/>
<RowDefinition Height="50*" MaxHeight="70"/>
</Grid.RowDefinitions>
<Border BorderThickness="0" BorderBrush="Red" Background="#FFF7F7F7" CornerRadius="5,5,0,0" Grid.Row="0">
<Label Content="{Binding Name}" VerticalContentAlignment="Center" FontSize="18" FontWeight="Bold" HorizontalContentAlignment="Center"/>
</Border>
<Label x:Name="labelLessonAmount" Content="{Binding AmountLesson}" Grid.Row="1" VerticalContentAlignment="Center" FontSize="14" Background="#F7F7F7" VerticalAlignment="Stretch" HorizontalContentAlignment="Center" />
<ProgressBar x:Name="progressBar" Grid.Row="2" Value="20" />
<Button x:Name="btnStartCourse" Content="Start" BorderThickness="0" Style="{DynamicResource ButtonStyleListViewBox}" Grid.Row="3" Command="{x:Static commands:CourseOverviewWindowCommands.StartCourse}" CommandParameter="{Binding}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
答案 0 :(得分:0)
您应该将value
绑定到Label
类的属性并设置此属性的值:
Course
要使其正常工作,foreach (Course c in items)
{
course.AmountLesson = context.Lessons.Where(l => l.CourseId == c.CourseId).Count();
}
类必须实现Course
接口,并在源属性(INotifyPropertyChanged
)设置为新值时引发PropertyChanged
事件:
AmountLesson
换句话说,您不直接访问public class Course : INotifyPropertyChanged
{
private int _amountLesson;
public int AmountLesson
{
get { return _amountLesson; }
set
{
_amountLesson = value;
OnPropertyChanged("AmountLesson");
}
}
//...
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string property)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
}
,而是设置Label
绑定的源属性。顺便说一句,您应该将Label
替换为Label
。