停止多次触发复选框事件

时间:2017-01-18 16:10:06

标签: c# wpf

所以我遇到一个问题,我将GridView的ItemsSource绑定到一个对象集合。我还有一列复选框,可用于选择用户希望删除的对象和所有相关项目。我遇到的问题是,当用户选择一个项目时,我会陷入持续选择项目的循环中。有没有人知道如何阻止这些复选框的程序选择来触发Checked事件。

正在使用的物业:

List<MyObject> _localCollection = new List<MyObject>();
List<MyObject> LocalCollection
{
   get { return _localCollection; }
   set
   {
     _localCollection = value;
     OnPropertyChanged("LocalCollection");
   }
}

XML代码的简单示例:

<GridView Name="grdItems">
  <GridViewColumn>
    <GridViewColumn.Header>
      <CheckBox/>
    </GridViewColumn.Header>
    <!--Column Template-->
    <GridViewColumn.CellTemplate>
      <DataTemplate>
         <StackPanel Orientation="Horizontal">
           <CheckBox Tag="{Binding ObjID}"
                     IsChecked="{Binding ToRemove, Mode=OneWay}"
                     Checked="SelectRelative" />
         </StackPanel>
      </DataTemplate>
    </GridViewColumn.CellTemplate>
  </GridViewColumn>

“SelectRelative”方法如下所示:

 private void SelectRelative(object sender, RoutedEventArgs e)
 {
    Dispatcher.BeginInvoke((Action)(() =>
    {
      //Get the Object Id we need
      int selectedId = Convert.ToInt32(((CheckBox)sender).Tag);
      //Get all objects that share this ID
      List<MyObjects> objLst = new List<MyObjects>(((IEnumerable<MyObjects>)grdItems.ItemsSource));

      //Clear the local collection property of our items used in the items source
      LocalCollection.Clear();
      //Remove the items source since we are updating it
      grdItems.ItemsSource = null;
      //Go through each item in the list and if the object id's match select them to remove
      foreach(var item in objLst)
      {
        if(item.ObjId == selectedId)
          item.ToRemove = true;
        //Add the object to our property
        LocalCollection.Add(item);
      }
      //Re-establish the item source with our new collection
      grdItems.ItemsSource = LocalCollection;
    }));
 }

1 个答案:

答案 0 :(得分:0)

try this:

 <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <CheckBox x:Name="chkboxPaid" Checked="chkboxPaid_Checked" Content="check" Style="{StaticResource MaterialDesignCheckBox}"   IsChecked="{Binding Path=IsSelected, Mode=TwoWay,
                                          RelativeSource={RelativeSource FindAncestor,
                                          AncestorType={x:Type DataGridRow}}}"/>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>