Getting the ListItem of a Databound list in Silverlight
in my Silverlight 4 Application, I have an observable list of a user defined class
ObservableCollection<MyClass> myList;
public class MyClass
{
public string Name { get; set; }
public string Value { get; set; }
}
I display this list in a ListBox, using databinding and a Template for the ListBoxItems:
<ListBox x:Name="ListBoxCharacteristics" Background="{x:Null}" HorizontalAlignment="Left" >
<!-- DataTemplate to display the content -->
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel x:Name="StackPanelBorder" Orientation="Horizontal" HorizontalAlignment="Left">
<TextBox x:Name="TextBoxCharacteristicName" Style="{StaticResource InputTextBox}" Text="{Binding Name}" />
<TextBox x:Name="TextBoxSep" Style="{StaticResource ReadOnlyTextBox}" Text="=" />
<TextBox x:Name="TextBoxValue" Style="{StaticResource InputTextBox}" Text="{Binding Value}" LostFocus="FormulaTextBox_LostFocus" TextChanged="Formula_TextChanged"/>
<Button x:Name="ButtonCheck" Style="{StaticResource RoundWebdingButton}" Content="s" Click="ButtonCheck_Click" />
<Button x:Name="ButtonAccept" Style="{StaticResource RoundWebdingButton}" Content="a" Click="ButtonAccept_Click" />
<Button x:Name="ButtonRemove" Style="{StaticResource RoundWebdingButton}" Content="r" Click="ButtonRemove_Click" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalAlignment" Value="Left" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
The user can change the values in the textboxes and can use the buttons to verify the input, accept it (write it to the underlying model) or remove the entry. To manipulate the underlying model, I need to access the associated item (that is displayed in the listboxitem, where the user has clicked the button).
One idea to get the item was to use the SelectedItem - Property, which will contain the wanted instance of MyClass. Problem is, that clicking on a button or a textbox doesn't select the containing ListBoxItem. The user would have to manually select the Listboxitem first by clicking somewhere at the item, where no textbox or button is displayed. Otherwise, SelectedItem will be null. I could get the TextBoxCharac开发者_Go百科teristicName TextBox via the parent object of the Button, but as the user shall be able to change this content too, I would be unable to get the correct item using this property as identifier.
Any other idea, how to find out, which MyClass-instance is the one that is displayed in the corresponding ListBoxItem?
Thanks in advance,
FrankFound it! The Button has a property "DataContext", that contains the MyClass-object I was looking for!
精彩评论