【问题标题】:WPF - Combobox of Checkboxes - Binding IsSelected?WPF - 复选框的组合框 - 绑定 IsSelected?
【发布时间】:2010-11-12 17:58:21
【问题描述】:

我已经实现了一个 CheckBox 组合框,它在 GUI 中看起来相当不错,但是我在以功能方式使用它时遇到了问题。

我遇到的主要问题是弄清楚实际选中了哪些框。在运行时,ComboBox.SelectedItem 工作正常,但如果我遍历所有项目,它们总是返回 IsSelected == false。

有什么想法吗?

这是我的 xaml:

<ComboBox Name="cboParam3" Grid.Row="0" Grid.Column="5" SelectedValuePath="Key" KeyDown="headerBar_KeyDown">
   <ComboBox.ItemTemplate>
      <DataTemplate>
         <StackPanel Orientation="Horizontal">
            <CheckBox IsChecked="{Binding Path=IsSelected}" VerticalAlignment="Center" Margin="0,0,4,0" />
            <TextBlock Text="{Binding Value}" VerticalAlignment="Center"/>
         </StackPanel>
      </DataTemplate>
   </ComboBox.ItemTemplate>
</ComboBox>

这是我最初填充组合框的代码:

Dictionary<int, string> codes = CodeCache.CodeLookup<DACaseCategoryCode>();
List<MultipleComboItem> items = new List<MultipleComboItem>();

codes.ToList().ForEach(t =>
{
   MultipleComboItem item = new MultipleComboItem();

   item.Key = t.Key;
   item.Value = t.Value;
   item.IsSelected = false;

   items.Add(item);
});

this.lblParam3.Content = "Case Category:";
this.cboParam3.ItemsSource = items;

还有什么我需要添加到组合中才能使其工作的吗?

谢谢,
桑尼

PS MultipleComboItem 只是一个具有三个属性的简单结构。那里没有什么特别的事情发生。

【问题讨论】:

    标签: wpf templates binding checkbox


    【解决方案1】:
    <ComboBox Name="identifiercombo" Text="{Binding SelectedIdentifier, UpdateSourceTrigger=PropertyChanged}"  ItemsSource="{Binding IdentifierCollection}"  SelectedIndex="0" IsEditable="True" Grid.Row="3" Grid.Column="1" HorizontalAlignment="Stretch" Margin="10,5">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <CheckBox Click="CheckBox_Click" Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content,UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center"/>                            
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
    

    【讨论】:

      【解决方案2】:

      编辑:

      我编写了一个快速测试应用程序,使用以下方法绑定似乎可以正常工作(但是,选中复选框不会设置组合框的 SelectedItem 属性):

      <Window x:Class="TestApp11.MainWindow" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:l="clr-namespace:TestApp11"
        Title="Window1" >
          <Window.Resources>
          </Window.Resources>
          <Grid Background="Black">
              <Grid.ColumnDefinitions>
                  <ColumnDefinition Width="Auto" />
              </Grid.ColumnDefinitions>
              <Grid.RowDefinitions>
                  <RowDefinition Height="Auto" />
                  <RowDefinition Height="Auto" />
              </Grid.RowDefinitions>
              <ComboBox Name="cboParam3" Grid.Row="0" Grid.Column="0">
                  <ComboBox.ItemTemplate>
                      <DataTemplate>
                          <StackPanel Orientation="Horizontal">
                              <CheckBox IsChecked="{Binding Path=Select}" VerticalAlignment="Center" Margin="0,0,4,0" />
                              <TextBlock Text="{Binding Name}" VerticalAlignment="Center"/>
                          </StackPanel>
                      </DataTemplate>
                  </ComboBox.ItemTemplate>
                  </ComboBox>
              <Button Grid.Row="1" Content="Click Me For Break Point" Click="Button_Click"></Button>
          </Grid>
      </Window>
      
      
      using System.Collections.ObjectModel;
      using System.Windows;
      
      namespace TestApp11
      {
      /// <summary>
      /// Interaction logic for MainWindow.xaml
      /// </summary>
      public partial class MainWindow : Window
      {
          public ObservableCollection<MCI> MCIList { get; set; }
          public MainWindow()
          {
              InitializeComponent();
              this.MCIList = new ObservableCollection<MCI>();
              this.cboParam3.ItemsSource = this.MCIList;
      
              this.MCIList.Add(new MCI());
              this.MCIList.Add(new MCI());
              this.MCIList.Add(new MCI());
          }
      
          private void Button_Click(object sender, RoutedEventArgs e)
          {
      
          }
      
      }
      
      public class MCI
      {
          public bool Select { get; set; }
          public string Name { get; set; }
          public MCI()
          {
              this.Name = "Bob";
              this.Select = false;
          }
      }
      }
      

      你做的事情与我上面所做的有很大不同吗?

      【讨论】:

      • 我更改属性名称时没有区别。
      • 我已经编辑了我的解决方案以显示一个正确绑定的快速示例项目。听起来你所拥有的应该正确绑定属性......但我不认为单击复选框应该设置 combobox.selected 项目属性。在我上面提供的示例中。单击项目的复选框与单击文本“Bob”产生不同的结果。 (后者设置 cboParam3.selecteditem,只需单击复选框将更新 MCI 对象的 Select 属性,但不会设置 cboParam3.SelectedItem 属性。希望这会有所帮助!
      • 鉴于我可以选中多个复选框,我怎样才能获得多选项目? ComboBox 的 ItemSource 包含我所有的 MCI,但是当我选中其中一个复选框时,Selected 属性似乎没有设置为真或假...
      • 如果您在新项目中使用我上面发布的代码...您还有问题吗?它似乎可以为我正确设置 Selected 属性。我问的原因是我想知道您的代码中是否还有其他内容可以重置 itemssource,或重新初始化您的 List items 对象///
      • 斯科特,是的。我在运行时多次重置 ItemSource。我的 Combobox 提供了一组在报表中使用的参数以及用于多个报表的屏幕本身,因此参数会根据显示的报表而变化。
      【解决方案3】:

      ComboBox.SelectedItem 工作正常

      好的,你可以得到选中的MultipleComboItem。

      如果我遍历所有项目,它们总是返回 IsSelected == false。

      那是因为你绑定了 IsChecked="{Binding Path=IsSelected}",如果你在打开的组合框列表中选中复选框并再次遍历项目,你可以找到 IsSelected == true 的项目。

      因此,如果您不选中复选框,则不会找到 IsSelected == true。

      您必须感觉到组合框的选中项和呈现该项的选中复选框之间的区别。

      【讨论】:

      • 是的。我不关心 ComboBox 的 SelectedItem。我需要找到选中了哪些复选框。我当时想说的是,当我检查 SelectedItem(它是 MultipleComboItems 之一)时,它正确显示了 Selected 属性。但是,当我遍历所有 ComboBox.Items 时,似乎没有被选中。
      【解决方案4】:

      我需要创建一个自定义复选框组合框,以显示日历月份列表供用户选择。此应用程序将允许用户选择月份,并且无论何时选择或取消选择月份,都会更新列表框。我遍历作为组合框的 itemsource 的 observable 集合,以确定检查了哪些月份。我可以使用 LINQ 来查询集合,而不是手动迭代可观察的集合,但那是另一天的事了。如果您想对此进行测试,只需创建一个名为 CustomComboBox 的新 wpf 应用程序(在 C# 中),然后将 xaml 和 c# 复制并粘贴到您的应用程序中:

      <Window x:Class="CustomComboBox.MainWindow"
              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
              Title="MainWindow" Height="350" Width="525">
          <Window.Resources>
      
          </Window.Resources>
          <Grid>      
              <Grid>
                  <Grid.RowDefinitions>
                      <RowDefinition Height="30" />
                      <RowDefinition Height="30"/>
                      <RowDefinition Height="Auto"/>
                  </Grid.RowDefinitions>
                  <Grid.ColumnDefinitions>
                      <ColumnDefinition />
                      <ColumnDefinition />            
                  </Grid.ColumnDefinitions>
                  <Label Grid.Column="0" Grid.Row="0" Content="Select the months:" />
                  <Label Grid.Column="1" Grid.Row="1" Content="Months selected:" />
                  <ComboBox x:Name="ComboBoxMonths" Grid.Column="0" Grid.Row="1">
                      <ComboBox.ItemTemplate>
                          <DataTemplate>
                              <StackPanel Orientation="Horizontal">
                                  <CheckBox IsChecked="{Binding Path=monthSelected}" VerticalAlignment="Center" Margin="0,0,4,0" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked" />
                                  <TextBlock Text="{Binding monthName}" VerticalAlignment="Center"/>
                              </StackPanel>
                          </DataTemplate>
                      </ComboBox.ItemTemplate>
                  </ComboBox>
                  <ListBox x:Name="ListBoxMonthsChecked" Grid.Column="1" Grid.Row="2">
                      <ListBox.ItemTemplate>
                          <DataTemplate>
                              <TextBlock Text="{Binding monthName}" VerticalAlignment="Center"/>
                          </DataTemplate>
                      </ListBox.ItemTemplate>
                  </ListBox>
              </Grid>       
          </Grid>
      
      </Window>
      

      c#代码:

      using System;
      using System.Collections.Generic;
      using System.Collections.ObjectModel;
      using System.ComponentModel;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;
      using System.Windows;
      using System.Windows.Controls;
      using System.Windows.Data;
      using System.Windows.Documents;
      using System.Windows.Input;
      using System.Windows.Media;
      using System.Windows.Media.Imaging;
      using System.Windows.Navigation;
      using System.Windows.Shapes;
      
      namespace CustomComboBox
      {
          /// <summary>
          /// Interaction logic for MainWindow.xaml
          /// </summary>
          public partial class MainWindow : Window
          {
              public static ObservableCollection<Month> monthList = new ObservableCollection<Month>();
              public static ObservableCollection<Month> monthsChecked = new ObservableCollection<Month>();
      
              public MainWindow()
              {
                  InitializeComponent();
      
                  this.ComboBoxMonths.ItemsSource = monthList;
                  this.ListBoxMonthsChecked.ItemsSource = monthsChecked;
      
                  //add Months to the ComboBoxMonths
                  monthList.Add(new Month() { monthSelected = false, monthName = "January", monthNumber = 01 });
                  monthList.Add(new Month() { monthSelected = false, monthName = "February", monthNumber = 02 });
                  monthList.Add(new Month() { monthSelected = false, monthName = "March", monthNumber = 03 });            
                  monthList.Add(new Month() { monthSelected = false, monthName = "April", monthNumber = 04 });
                  monthList.Add(new Month() { monthSelected = false, monthName = "May", monthNumber = 05 });
                  monthList.Add(new Month() { monthSelected = false, monthName = "June", monthNumber = 06 });
                  monthList.Add(new Month() { monthSelected = false, monthName = "July", monthNumber = 07 });
                  monthList.Add(new Month() { monthSelected = false, monthName = "August", monthNumber = 08 });
                  monthList.Add(new Month() { monthSelected = false, monthName = "September", monthNumber = 09 });
                  monthList.Add(new Month() { monthSelected = false, monthName = "October", monthNumber = 10 });
                  monthList.Add(new Month() { monthSelected = false, monthName = "November", monthNumber = 11 });
                  monthList.Add(new Month() { monthSelected = false, monthName = "December", monthNumber = 12 });
              }
      
              public class Month
              {
                  public string monthName { get; set; } 
                  public int monthNumber { get; set; } 
      
                  private bool _monthSelected;
                  public bool monthSelected //the checkbox is bound to this
                  {
                      get
                      {
                          return _monthSelected;
                      }
                      set
                      {
                          if (value != this._monthSelected)
                          {
                              _monthSelected = value;                        
                          }
                      }
                  }
      
              }
      
              private void CheckBox_Checked(object sender, RoutedEventArgs e)
              {
                  monthsChecked.Clear();
                  foreach (Month m in monthList)
                  {
                      if (m.monthSelected == true)
                      {                    
                          monthsChecked.Add(m);
                      }
                  }            
              }
      
              private void CheckBox_UnChecked(object sender, RoutedEventArgs e)
              {
                  monthsChecked.Clear();
                  foreach (Month m in monthList)
                  {
                      if (m.monthSelected == true)
                      {
                          monthsChecked.Add(m);
                      }
                  }
              }
      
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2014-11-24
        • 1970-01-01
        • 2017-07-04
        • 2012-06-18
        • 2011-03-09
        • 1970-01-01
        相关资源
        最近更新 更多