2010-07-08 49 views
0

在我的Silverlight 4應用程序,我有一個用戶定義的類獲取數據綁定列表的列表項在Silverlight

ObservableCollection<MyClass> myList; 

public class MyClass 
{ 
    public string Name { get; set; } 
    public string Value { get; set; } 
} 

我ListBox中顯示此列表中可觀察到的列表,使用數據綁定併爲模板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> 

用戶可以改變這些值在文本框,並且可以使用按鈕來驗證輸入,接受它(它寫入基礎模型)或刪除的條目。要操縱底層模型,我需要訪問關聯的項目(顯示在用戶點擊按鈕的listboxitem中)。

獲得該項目的一個想法是使用SelectedItem - Property,它將包含MyClass的所需實例。問題是,單擊按鈕或文本框不會選擇包含ListBoxItem。用戶必須先手動選擇Listboxitem,方法是單擊不顯示文本框或按鈕的項目。否則,SelectedItem將爲空。 我可以通過按鈕的父對象獲取TextBoxCharacteristicName文本框,但由於用戶也應該能夠更改此內容,所以我將無法使用此屬性作爲標識符來獲取正確的項目。

任何其他想法,如何找出哪個MyClass實例是顯示在相應ListBoxItem中的?

由於提前,
弗蘭克

回答

0

找到了! Button有一個屬性「DataContext」,它包含我正在尋找的MyClass對象!