C# WPF ListBox Checkbox Binding IsChecked to a Field and IsSelected?

后端 未结 4 1222
天涯浪人
天涯浪人 2021-02-06 01:09

I\'m trying to bind a CheckBox to a field but also trigger the checkbox\'s IsSelected.

Here is the ListBox setup that is working with the Binding to data



        
相关标签:
4条回答
  • 2021-02-06 01:15

    you can use a MultiBinding with MultiConverter

    <CheckBox.IsChecked>
    <MultiBinding Converter="{StaticResource YourMultiBindConverter}"> 
                    <Binding Path="IsSelected" RelativeSource={RelativeSource AncestorType=ListBoxItem}"/> 
                    <Binding Path="Checked"/> 
     </MultiBinding> 
    </CheckBox.IsChecked>
    

    and create a YourMultiBindConverter that implement IMultiValueConverter

    0 讨论(0)
  • 2021-02-06 01:16

    Would it work to bind both UI properties to the Checked object model property?

    <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="IsSelected" Value="{Binding Checked, Mode=OneWay}"/>
        </Style>
    </ListBox.ItemContainerStyle>
    
    <ListBox.ItemTemplate>
       <DataTemplate>
          <CheckBox Content="{Binding Text}" IsChecked="{Binding Checked}"/>
       </DataTemplate>
    </ListBox.ItemTemplate>
    
    0 讨论(0)
  • 2021-02-06 01:20

    Ok, I answered my own question (and there might better to do this so feel free to add) I added a Click event to the checkbox like so

    <ListBox x:Name="lstExclude"  Grid.Column="2" SelectionMode="Single" >
     <ListBox.ItemTemplate>
        <DataTemplate>
          <CheckBox  Content="{Binding Text}" 
              IsChecked="{Binding Checked ,Mode=TwoWay}" Click="CheckBox_Click"/>
          </DataTemplate>
     </ListBox.ItemTemplate>
    </ListBox>
    

    and then added this code for the Click Event

    private void CheckBox_Click(object sender, RoutedEventArgs e)
    {
        var cb = sender as CheckBox;
        var item = cb.DataContext;
        lstExclude.SelectedItem = item;
    }
    

    Now the item gets selected when you click the checkbox (checked or unchecked) and the item is available to the 'lstExclude.SelectedIndex' method

    I hope this helps anybody coming along with the same problem.

    0 讨论(0)
  • 2021-02-06 01:31
     <CheckBox Padding="10" 
               IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type  
                                                     ListBoxItem}}, Path=IsSelected}">
            <CheckBox.LayoutTransform>
                      <ScaleTransform ScaleX="1" ScaleY="1" />
            </CheckBox.LayoutTransform>
      </CheckBox>
    
    0 讨论(0)
提交回复
热议问题