Home > Back-end >  Extract TextBlock value from a ComboBox DataTemplate WPF DataGrid
Extract TextBlock value from a ComboBox DataTemplate WPF DataGrid

Time:09-24

I have a multiselect ComboBox with the following template:

 <ComboBox.ItemTemplate>
        <DataTemplate>
              <StackPanel Orientation="Horizontal">
                   <CheckBox
                         VerticalAlignment="Center"
                         Checked="checkBox_Checked"
                         ClickMode="Press"
                         Unchecked="checkBox_Unchecked" />
                   <TextBlock Text="{Binding Position}" />
              </StackPanel>
        </DataTemplate>
 </ComboBox.ItemTemplate>

My question is, if the checkBox is checked, how could I get the value from the TextBlock (what should be the code in checkBox_Checked? I will be needing it for further use.

CodePudding user response:

There shouldn't be any Checked or Unchecked event handler.

Instead, the view model (that exposes the Position property) should expose another property, to which you bind the IsChecked property of the CheckBox:

<DataTemplate>
    <StackPanel Orientation="Horizontal">
        <CheckBox IsChecked="{Binding Checked}" />
        <TextBlock Text="{Binding Position}" />
    </StackPanel>
</DataTemplate>

In the setter of the Checked property you can access the Position property.

Also be aware that the TextBlock in the ItemTemplate seems to be redundant:

<DataTemplate>
    <CheckBox IsChecked="{Binding Checked}"
              Content="{Binding Position}" />
</DataTemplate>
  • Related