In my Silverlight 3 project, I'm using a ListBox to display results of a Get() operation form a WCF WebService.
The ListBox's item template is the following :
<ListBox x:Name="m_listview" ItemsSource="{Binding Users, Mode=TwoWay, UpdateSourceTrigger=Default}" Foreground="{StaticResource EnergyBlue}" Background="{StaticResource EnergyBackground}" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Center" Grid.ColumnSpan="3" Margin="0,0,0,2" IsSynchronizedWithCurrentItem="False">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid MinWidth="536" MinHeight="10" d:DesignWidth="19.875" d:DesignHeight="20.75">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.2*"/>
<ColumnDefinition Width="0.2*"/>
<ColumnDefinition Width="0.2*"/>
<ColumnDefinition Width="0.2*"/>
<ColumnDefinition Width="0.2*"/>
</Grid.ColumnDefinitions>
<TextBox Text="{Binding Path=UserName, Mode=TwoWay, UpdateSourceTrigger=Default}" Grid.Column="0" Foreground="{StaticResource EnergyWhite}" Margin="2" Background="{StaticResource EnergyBackground}" BorderBrush="{StaticResource EnergyBlue}" SelectionBackground="{StaticResource EnergyBlue}" SelectionForeground="{StaticResource EnergyWhite}" MinWidth="100"/>
<PasswordBox Password="{Binding Path=UserPass, Mode=TwoWay, UpdateSourceTrigger=Default}" Grid.Column="1" Foreground="{StaticResource EnergyWhite}" Margin="2" Background="{StaticResource EnergyBackground}" BorderBrush="{StaticResource EnergyBlue}" SelectionBackground="{StaticResource EnergyBlue}" SelectionForeground="{StaticResource EnergyWhite}" MinWidth="100"/>
<TextBox Text="{Binding Path=UserTypeId, Mode=TwoWay, UpdateSourceTrigger=Default}" Grid.Column="2" Foreground="{StaticResource EnergyWhite}" Margin="2" Background="{StaticResource EnergyBackground}" BorderBrush="{StaticResource EnergyBlue}" SelectionBackground="{StaticResource EnergyBlue}" SelectionForeground="{StaticResource EnergyWhite}" MinWidth="100"/>
<Button Style="{StaticResource EnergyGlassButton}" Grid.Column="3" MinWidth="10" MinHeigh开发者_如何学运维t="10" Content="Update" Click="OnUpdateUser"/>
<Button Style="{StaticResource EnergyGlassButton}" Grid.Column="4" MinWidth="10" MinHeight="10" Content="Remove" Click="OnRemoveUser"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The template contains 2 buttons. When I click either of them, I'd like to obtain a reference to the exact data-item under the listboxitem. How do I do that? I've tried :
User target_user = m_listview.SelectedItem as User;
but it turned out that the listview item wasn't selected. Can it be done without actually selecting the listview item? For instance, just click on the "remove" button and have the row disappear?
Best regards
I believe the following ought to retrieve the Item you require:-
void OnUpdateUser(object sender, RoutedEventArgs e)
{
object item = ((Button)sender).DataContext;
// do stuff with item
}
精彩评论