WPF listboxitem IsSelected绑定不起作用

时间:2014-02-05 00:53:49

标签: c# .net wpf

我将lisbox控件的 ItemsSource 绑定到 ObservableCollection<Course> 课程类的属性为 IsSelected 。 Course的IsSelected属性绑定到ListBoxItem的IsSelected,如下所示:

 <ListBox ItemsSource="{Binding Courses}" SelectionMode="Extended"
      ItemContainerStyle="{StaticResource ContainerStyle}"/>


 <Style TargetType="{x:Type ListBoxItem}"  x:Key="ContainerStyle">
        <Setter Property="IsSelected" Value="{Binding Path=IsSelected}"/>
        <Setter Property="ContentTemplate" Value="{StaticResource CourseTemplate}" />
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="true">
                <Setter Property="ContentTemplate" Value="{StaticResource SelectedCourseTemplate}" />
            </Trigger>
        </Style.Triggers>
 </Style>

屏幕上有一个按钮,可在单击时执行命令。该命令调用迭代List的方法,并将IsSelected设置为true / false。当在Course对象上将IsSelected设置为true时,将应用“SelectedCourseTemplate”,但是当它设置为false时,“CourseTemplate”不会被应用。

此外,由于列表框处于“扩展”选择模式,我希望能够在用户选择列表中的多个项目时在相应的Course对象上设置IsSelected属性。

更新** 课程类如下

public class Course : INotifyPropertyChanged
{
    private bool _isSelected;
    public event PropertyChangedEventHandler PropertyChanged;

        public bool IsSelected
        {
            get { return _isSelected; }
            set
            {
                _isSelected = value;
                RaisePropertyChangedNotification("IsSelected");
            }
        }

 private void RaisePropertyChangedNotification(string propName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }
}

已更新

<DataTemplate x:Key="CourseTemplate">
    <Grid HorizontalAlignment="Stretch" Margin="0">
        <Grid.RowDefinitions>
            <RowDefinition Height="100"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
           <!-- Bunch of column definitions here -->
        </Grid.ColumnDefinitions>

       <!-- Textbox, StackPanel etc set in each of the columns here -->

    </Grid>
</DataTemplate>

由于

0 个答案:

没有答案