Wpf 从数据模板中的组合框获取SelectedItem

Wpf 从数据模板中的组合框获取SelectedItem,wpf,datatemplate,Wpf,Datatemplate,假设我有一个这样的数据模板 <DataTemplate x:Key="Body"> <StackPanel Orientation="Horizontal"> <ComboBox ItemsSource="{Binding Path=Person.Children}"></ComboBox> <Button Click="Button_Click">Hello</Button> </S

假设我有一个这样的数据模板

 <DataTemplate x:Key="Body">
   <StackPanel Orientation="Horizontal">
     <ComboBox ItemsSource="{Binding Path=Person.Children}"></ComboBox>
     <Button Click="Button_Click">Hello</Button>
   </StackPanel>
 </DataTemplate>

不要使用
单击
事件处理程序,而是使用
命令
并将
命令参数
属性绑定到
组合框。选择editem
。然后,在命令的执行逻辑中,您可以使用参数。

如果给组合框命名,您还可以在codebehind中引用该组合框。然而,使用一个单独的类来完成逻辑比使用后面的代码更简洁。例如viewmodel

然后你也可以这样做

            <DataTemplate x:Key="Body">
                <StackPanel Orientation="Horizontal">
                    <ComboBox ItemsSource="{Binding Path=Person.Children}"
                        SelectedItem="{Binding Path=SelectedChild}"
                        IsSynchronizedWithCurrentItem="True"/>
                    <Button Command="{Binding Path=ButtonCommand}">Hello</Button>
                </StackPanel>
            </DataTemplate>

你好
            <DataTemplate x:Key="Body">
                <StackPanel Orientation="Horizontal">
                    <ComboBox ItemsSource="{Binding Path=Person.Children}"
                        SelectedItem="{Binding Path=SelectedChild}"
                        IsSynchronizedWithCurrentItem="True"/>
                    <Button Command="{Binding Path=ButtonCommand}">Hello</Button>
                </StackPanel>
            </DataTemplate>