Silverlight中可编辑的文本框列表框

时间:2012-11-13 23:01:21

标签: c# 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" }; }
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个:

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