Tor*_*ups 3 data-binding windows-phone
我有一个包含一个简单按钮的ItemTemplate.当我单击此按钮时,我需要一种方法来识别单击的行以拉出绑定到列表框的项目.
XAML
<ListBox Name="DemoBox" SelectionChanged="listBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Height="150">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="400"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid Height="120" Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="60"/>
</Grid.RowDefinitions>
<TextBlock
Grid.Row="0"
Text="{Binding SomeObjProperty}"/>
</Grid>
<Grid Height="120" Grid.Column="1" Margin="0,-12,0,0">
<Button Click="ShowStuffOnMap_Click">
<Button.Background>
<ImageBrush ImageSource="images/arrow.png"/>
</Button.Background>
</Button>
</Grid>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Run Code Online (Sandbox Code Playgroud)
点击处理程序
private void ShowStuffOnMap_Click(object sender, RoutedEventArgs e)
{
//sender is the button so ...
}
Run Code Online (Sandbox Code Playgroud)
先感谢您
为什么在带有SelectionChanged事件的ListBox中有一个带有单击事件的Button?如果他们有不同的行动,这可以弥补一些可怕的用户体验!
通常的方法是使用数据绑定ListBox,然后使用SelectionChanged事件读出所选项.
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var listBox = sender as ListBox;
var selectedItem = listBox.SelectedItem as MyDataBoundType;
if (selectedItem != null)
{
// do stuff
}
// if you use the ListBox for navigation, set the SelectedIndex to -1
// listBox.SelectedIndex = -1;
}
Run Code Online (Sandbox Code Playgroud)
但如果你真的想要这样做,你需要使用该Tag属性.
<Button Click="ShowStuffOnMap_Click" Tag="{Binding}">
Run Code Online (Sandbox Code Playgroud)
然后在你的事件处理程序中:
private void ShowStuffOnMap_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button;
var selectedItem = button.Tag as MyDataBoundType;
}
Run Code Online (Sandbox Code Playgroud)
但我仍然认为你的方法是错误的,并且代表糟糕的用户体验,因为列表的常规方法是列表中的整行只是一个选择.
| 归档时间: |
|
| 查看次数: |
2459 次 |
| 最近记录: |