假设我有一个像这样的DataTemplate
<DataTemplate x:Key="Body">
<StackPanel Orientation="Horizontal">
<ComboBox ItemsSource="{Binding Path=Person.Children}"></ComboBox>
<Button Click="Button_Click">Hello</Button>
</StackPanel>
</DataTemplate>
其中显示了一个ComboBoxes列表,后跟一个按钮。
现在,点击按钮我需要在按下的按钮旁边的组合中发现值。我可以获得如下的数据上下文,但无法弄清楚如何获得组合SelectedItem
private void Button_Click(object sender, RoutedEventArgs e)
{
// Can get the data context
var p = ((Button)sender).DataContext as Person;
// How to get the value in the combo ...?
}
答案 0 :(得分:0)
不使用Click
事件处理程序,而是使用Command
并将CommandParameter
属性绑定到ComboBox.SelectedItem
。然后在命令的执行逻辑中,您可以使用参数。
答案 1 :(得分:0)
如果你给它命名,你也可以在代码隐藏中引用组合框。然而,使用单独的类来完成逻辑比使用后面的代码更清洁。比如一个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>