2012-11-13 75 views
0

我的目標是能夠添加/編輯/刪除項目到列表框。我以下面的方式創建了一個文本框列表框。我能夠顯示數據,但我無法編輯數據。有人可以幫助我修改代碼,以便我可以實現此功能。Silverlight中文本框的可編輯列表框

<ListBox Name="lbDemoBox" ItemsSource="{Binding testList}" Grid.Column="0" Grid.Row="0" SelectionChanged="lbDemoBox_SelectionChanged"> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <StackPanel Orientation="Vertical"> 
        <TextBox Text="{Binding Path=.}" KeyDown="TextBox_KeyDown" KeyUp="TextBox_KeyUp" GotFocus="TextBox_GotFocus"/> 
       </StackPanel> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 

這裏是背後

public partial class MainPage : UserControl 
{ 
    private string focusedString { get; set; } 

    public MainPage() 
    { 
     InitializeComponent(); 
    } 

    private void Window_Loaded(object sender, RoutedEventArgs e) 
    { 
     LayoutRoot.DataContext = new ViewModel(); 
    } 

    private void TextBox_KeyDown(object sender, KeyEventArgs e) 
    { 
     if (e.Key == Key.Enter && (Keyboard.Modifiers & (ModifierKeys.Shift)) == ModifierKeys.Shift) 
     { 
      (lbDemoBox.ItemsSource as ObservableCollection<string>).Add(string.Empty); 
     } 



    } 

    private void TextBox_KeyUp(object sender, KeyEventArgs e) 
    { 

     if (e.Key == Key.Delete) 
     { 
      int index = (lbDemoBox.ItemsSource as ObservableCollection<string>).IndexOf(focusedString); 

      (lbDemoBox.ItemsSource as ObservableCollection<string>).RemoveAt(index); 

     } 
    } 

    private void TextBox_GotFocus(object sender, RoutedEventArgs e) 
    { 
     focusedString = (sender as TextBox).Text; 
    } 

    private void lbDemoBox_SelectionChanged(object sender, SelectionChangedEventArgs e) 
    { 

    } 

} 

public class ViewModel 
{ 
    public ObservableCollection<string> testList 
    { 
     get { return new ObservableCollection<string> { "Item1", "Item2", "Item3" }; } 
    } 
} 
+0

你是什麼意思編輯數據,您需要雙向綁定? –

+0

是的,我想要雙向綁定,當我設置Mode = TwoWay時,我得到一個異常「值不在預期範圍內」 – csprabala

回答

0

代碼試試這個:

<TextBox Text="{Binding Path=YourProperty, Mode=TwoWay}" /> 
+0

Dimitry,Path =。因爲我綁定到列表和我設置mode = twoway的時刻,我得到一個「值不在預期範圍內」異常 – csprabala