0
votes

I saw something about this, but I've lost it now, and can't find it again. What I need is to know which ListViewItem a checkbox exists in, when the checkbox is checked (Which will eventually lead to its deletion),

I tried getting the parent, but apparently that doesn't work.

XAML:

<ListView Name="incomingMessages" Extensions:ListViewColumns.Stretch="true"
  Height="226" Canvas.Left="0" Canvas.Top="0" Width="755" ItemsSource="{Binding Messages}">
  <ListView.View>
    <GridView>
      <GridViewColumn Header="Time" Width="100" DisplayMemberBinding="{Binding Time}" />
      <GridViewColumn Header="Message" DisplayMemberBinding="{Binding FullMessage}"  />
      <GridViewColumn Header="Phone Number" DisplayMemberBinding="{Binding Number}" Width="85"  />
      <GridViewColumn Header="Done" Width="45">
        <GridViewColumn.CellTemplate>
          <DataTemplate>
            <CheckBox IsChecked="{Binding Done}" VerticalAlignment="Center" />
          </DataTemplate>
        </GridViewColumn.CellTemplate>
      </GridViewColumn>
    </GridView>
  </ListView.View>
</ListView>

What sort of code needs to go in the Checked event to make it work? (As a side question, why does my VerticalAlignment not center align my checkboxes in the column?)

Like I said I tried parent in this sort of code

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox cb = (CheckBox)sender;
            object lv = cb.parent;
        }

And if I breakpoint on the cb.parent line, cb.parent is null.

Thanks, Psy

2
do u need to check if the CheckBox is checked or not ? or u need to know the index of the item that has a checkbox in it's row?Ahmy
No, the checkbox will always start off as non-checked, and when the box is checked the row will get removed (it may change to a button depending on the clients wishes, but current spec is checkbox).Psytronic

2 Answers

0
votes

Ok, so what I've worked out is to do this

<CheckBox IsChecked="{Binding Done}"
  Uid="{
    Binding Path=Items.Count,
    Mode=OneTime,
    RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}
  }"
  Checked="CheckBox_Checked"
  VerticalAlignment="Center"
  HorizontalAlignment="Center" />

Which is working (aside from the first three which are added, because they are added at runtime and seem to bypass it, however that won't happen in live version so thats ok. But then I can see this leading to problems when deleted, as the Uid will be maintained, yet the DataSource will not match up. So ideas?

0
votes

You can use VisualTreeHelper to walk up the visual tree and find the ListViewItem. However, I'd recommend steering clear of this approach if possible. It is most likely possible to achieve your goal using other WPF features like data binding.