从 ComboBox DataTemplate WPF DataGrid 中提取 TextBlock 值

Extract TextBlock value from a ComboBox DataTemplate WPF DataGrid

我有一个多选 ComboBox,模板如下:

 <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>

我的问题是,如果复选框被选中,我如何从 TextBlock 中获取值(checkBox_Checked 中的代码应该是什么?我将需要它以供进一步使用。

不应有任何 Checked 或 Unchecked 事件处理程序。

相反,视图模型(公开 Position 属性)应该公开另一个 属性,您将 IsChecked 属性 绑定到它复选框:

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

在setter的Checked属性中可以访问Position属性.

另请注意,ItemTemplate 中的 TextBlock 似乎是多余的:

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