我正在创建一个WPF应用程序。我想在每个按钮点击时显示一个页面。
<ItemsControl ItemsSource="{Binding Path=DashBoardApps}" VerticalAlignment="Bottom" HorizontalAlignment="Center" Name="Abc">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Controls:FishEyeControl />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button MouseDown="Button_MouseDown">
<Image Source="{Binding Path=ApplicationImage}" Width="32" Height="32"/>
</Button>
<TextBlock x:Name="txtAppName" Text="{Binding Path=ApplicationName}" TextAlignment="Center" Visibility="Hidden" FontSize="7px" Foreground="#eff7ff" VerticalAlignment="Center"/>
</StackPanel>
<DataTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="txtAppName" Property="Visibility" Value="Visible" />
</Trigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
总共有6个按钮。在按钮上单击我想要显示一个页面。(不同按钮的不同页面)。 在后面的代码中,我做了类似的事情
private void Button_MouseDown(object sender, MouseButtonEventArgs e)
{
var s = sender as ItemsControl;
if (s == Abc.Items.GetItemAt(1))//if it is the first button. Not sure if it is right
{
//Code to display page
}
}
我想知道哪个按钮生成了该事件。如同,如果单击第一个按钮,则必须显示page1。所以我尝试使用GetItemAt()
函数来查看是否单击了第一个按钮(以显示第一页)。但它不起作用,我不确定这种方法是否正确。
P.S简单地说我想知道哪个按钮生成了事件 - 可以使用索引来完成。如果是这样,怎么样? 请帮助
答案 0 :(得分:3)
实际的Button传递给sender参数中的事件处理程序:
Button button = sender as Button;
但是有一个问题。由于Button处理MouseDown事件,因此您无法获得它。您必须为PreviewMouseDown事件添加处理程序,或者更好地为Button的Click事件添加处理程序。
正如注释:ItemCollection.GetItemAt方法使用从零开始的索引。
编辑:以下是如何将Button的Tag
属性绑定到ItemsControl的AlternationIndex
属性以及如何在Button的Click处理程序中使用该索引:
<ItemsControl ... AlternationCount="2147483647">
...
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button Click="Button_Click"
Tag="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},
Path=(ItemsControl.AlternationIndex)}">
...
</StackPanel>
...
</DataTemplate>
</ItemsControl.ItemTemplate>
使用XAML命名空间xmlns:sys="clr-namespace:System;assembly=mscorlib"
,您也可以写
<ItemsControl AlternationCount="{x:Static sys:Int32.MaxValue}">
点击处理程序:
private void Button_Click(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
int index = (int)button.Tag;
// get page by zero-based index
...
}