How to access a Checkbox inside Listbox?

前端 未结 5 1882
没有蜡笔的小新
没有蜡笔的小新 2021-01-03 14:40

I have a listbox and I have set the itemstemplate as shown below.

XAML:

            
                       


        
相关标签:
5条回答
  • 2021-01-03 15:15

    If you're already binding to the Title property in the item template then it would certainly make sense to bind to IsChecked, too.

    If you really need to, you can walk the visual tree by using the VisualTreeHelper to find the CheckBox instances.

    0 讨论(0)
  • 2021-01-03 15:19

    Binding the IsChecked property to a boolean property on your object instance contained within DataList would be the simplest and cleanest way. Alternatively, if you want to avoid code behind, then you could write an attached property.

    0 讨论(0)
  • 2021-01-03 15:25

    See also How to access a specific item in a Listbox with DataTemplate?

    0 讨论(0)
  • 2021-01-03 15:26

    I bet it cannot be simpler than that:

        <ListBox SelectionMode="Multiple" >
          <ListBox.ItemTemplate>
             <DataTemplate>
                <CheckBox   
                 IsChecked="{Binding Path=IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}"   
                   Content="{Binding Path=Content,    RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}"   />
             </DataTemplate>
          </ListBox.ItemTemplate>
        </ListBox>
    
    0 讨论(0)
  • Yes. One way to do is to bind the IsChecked property. And if you are using MVVM, probably that's the right way to do it.

    Anyways, if you don't want to go the binding way, and assuming you want to iterate over all items of listbox, and prepare a list of checked items, see if this helps: WPF - Find a Control from DataTemplate in WPF

    0 讨论(0)
提交回复
热议问题