如何在列表框中编写按钮的事件
本文关键字:按钮 事件 列表 | 更新日期: 2023-09-27 17:55:51
我有一个列表框。在里面,我有每行的按钮。当我单击该按钮时,页面将导航到另一个页面。如果我单击列表框项,页面将导航到另一个页面。
现在我无法在列表框中编写按钮的事件。
<Grid x:Name="ListBoxEventsUIContainer" Grid.Row="1" Margin="2,0,2,0">
<ListBox Height="444" ItemsSource="{Binding StudentDetails,Mode=TwoWay}" HorizontalAlignment="Left" Margin="2,34,0,0" Name="listBox1" VerticalAlignment="Top" Width="476" BorderBrush="#00410D0D">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Gray" Padding="5" BorderThickness="1">
<StackPanel Orientation="Horizontal">
<Border BorderBrush="Wheat" BorderThickness="1">
<Image Name="ListPersonImage" Source="{Binding PersonImage}" Height="100" Width="100" Stretch="Uniform" Margin="10,0,0,0"/>
</Border>
<TextBlock Text="{Binding FirstName}" Name="firstName" Width="200" Foreground="White" Margin="10,10,0,0" FontWeight="SemiBold" FontSize="22" />
<Button Height="80" Width="80" Command="{Binding addPerson}">
<Button.Background>
<ImageBrush ImageSource="/NewExample;component/Images/icon_increase.png" Stretch="Fill" />
</Button.Background>
</Button>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
我想为:-
<Button Height="80" Width="80" Command="{Binding addPerson}">
<Button.Background>
<ImageBrush ImageSource="/NewExample;component/Images/icon_increase.png" Stretch="Fill" />
</Button.Background>
</Button>
在视图模型中。通常我会写按钮事件,例如:-
ReactiveAsyncCommand addPerson = new ReactiveAsyncCommand();
public ListBoxEventsViewModel()
{
var getOrgDetails = new ReactiveAsyncCommand();
getOrgDetails.Subscribe(x =>
{
StudentDetails = new ObservableCollection<ListBoxEventsModel>();
StudentDetails = ListBoxEventsModel.extract(myData.ToString());
});
getOrgDetails.Execute(true);
addPerson = new ReactiveAsyncCommand();
addPerson.Subscribe(x=>{
MessageBox.Show("Selected..");
});
}
但是我可以添加人员按钮不起作用。请让我知道如何写事件?提前谢谢..
将DataContext
设置为按钮。
Xaml:
<Button DataContext="{Binding DataContext, ElementName=listBox1}"
Height="80"
Width="80"
Command="{Binding addPerson}">
<Button.Background>
<ImageBrush ImageSource="/NewExample;component/Images/icon_increase.png"
Stretch="Fill" />
</Button.Background>
您可以执行以下任何操作。
- 直接在项模板中编写"click"事件,然后获取调用它的相应数据项, 如下所示
在 XAML 中。
<Button Height="80" Width="80" Command="{Binding addPerson}" click="addPersonClick">
<Button.Background>
<ImageBrush ImageSource="/NewExample;component/Images/icon_increase.png" Stretch="Fill" />
</Button.Background>
</Button>
在后端..
private void addPersonClick(object sender, RoutedEventArgs e)
{
StudentsDetails object=(sender as Button).DataContext as StudentsDetails;
//You can use this object for any of your operations
}
阿拉伯数字。或者,您可以完全使用名为ContextMenu的新功能来实现所需的导航之一。