将值绑定到WPF ListBox中的标签

时间:2017-12-11 14:47:24

标签: c# wpf listbox

我在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>

1 个答案:

答案 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