[英]Editable Listbox of textboxes in 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" }; }
}
}
嘗試這個:
<TextBox Text="{Binding Path=YourProperty, Mode=TwoWay}" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.