[英]How to catch expander header button click event
I have an expander with button on the expander headers.我在扩展器标题上有一个带有按钮的扩展器。 I would like to know on which expanders header is clicked the button, because i should modify the data on the button_click event.
我想知道在哪个扩展器标题上单击了按钮,因为我应该修改 button_click 事件上的数据。 If I Don`t have binded it with a View Model
如果我没有将它与视图模型绑定
<Expander IsExpanded="True">
<Expander.Header>
<StackPanel Orientation="Horizontal">
<Button Name="btnAllDone" Click="btnAllDone_Click >Close
</Button>
</StackPanel>
</Expander.Header>
<Expander.Content>
<ItemsPresenter/>
</Expander.Content>
</Expander>
AND this is the click event这是点击事件
private void btnAllDone_Click(object sender, RoutedEventArgs e)
{
MessageBoxResult result = MessageBox.Show("Are you sure?", "All", MessageBoxButton.YesNo);
switch (result)
{
case MessageBoxResult.Yes:
try
{
//AND HERE I WANT TO MODIFY THE DATA(MYOBJECT) OF THE CURRENT EXPANDER HEADER GROUP
}
catch (Exception ex)
{
throw;
}
break;
case MessageBoxResult.No:
break;
}
}
looks like expander, button, and event handler correspond 1-to-1.看起来扩展器、按钮和事件处理程序是一一对应的。 so assign Name to expander, and use it in event handler:
因此将名称分配给扩展器,并在事件处理程序中使用它:
<Expander x:Name="expanderAllDone" IsExpanded="True">
<Expander.Header>
<StackPanel Orientation="Horizontal">
<Button Name="btnAllDone" Content="Close" Click="btnAllDone_Click"/>
</StackPanel>
</Expander.Header>
<Expander.Content>
<ItemsPresenter/>
</Expander.Content>
</Expander>
private void btnAllDone_Click(object sender, RoutedEventArgs e)
{
MessageBoxResult result = MessageBox.Show("Are you sure?", "All", MessageBoxButton.YesNo);
if (result != MessageBoxResult.Yes)
return;
try
{
expanderAllDone.IsExpanded = false;
}
catch (Exception ex)
{
throw;
}
}
那么你可以添加扩展器的名称属性,这样你就可以检查生成了哪个扩展器事件
Try this:尝试这个:
private static T GetParent<T>(DependencyObject child) where T : class
{
var parent = VisualTreeHelper.GetParent(child);
if (parent == null) return null;
else if (parent is T) return parent as T;
else return GetParent<T>(parent);
}
private void btnAllDone_Click(object sender, RoutedEventArgs e)
{
// Get current button
var button = (Button)sender;
// Get current expander
var expander = GetParent<Expander>(button);
// Toggle expander
expander.IsExpanded = !expander.IsExpanded;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.