我想構建一個場景,我可以從項目集合中選擇任何項目,並且可以通過單擊「添加」按鈕將此文本字符串添加到列表框或數據網格。我還需要能夠通過單擊「刪除」按鈕從列表框或數據網格中刪除項目。我開始這個,但有問題,使其工作。我想知道問題是什麼。任何想法都非常感謝。謝謝!如何將選定的項目從AutoCompleteBox添加到ListBox或Datagrid?
XAML:
<UserControl
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
x:Class="AutoCompleteBoxSimpleTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit"
mc:Ignorable="d" >
<StackPanel x:Name="LayoutRoot" Background="White" Width="150">
<TextBlock Text="{Binding ElementName=MyAutoCompleteBox, Path=SelectedItem, TargetNullValue='No item selected', StringFormat='Selected Item: {0}'}" />
<sdk:AutoCompleteBox x:Name="MyAutoCompleteBox" IsTextCompletionEnabled="True" ItemsSource="{Binding Items}" />
<Button x:Name="AddButton" Click="AddButton_Click" Content="AddButton" />
<Button x:Name="RemoveButton" Click="RemoveButton_Click" Content="RemoveButton" />
<ListBox x:Name="ListBox" BorderThickness="0" SelectionMode="Multiple" />
<sdk:DataGrid x:Name="dgEditPackageProperties_ADEntities">
<sdk:DataGrid.Columns>
<sdk:DataGridTemplateColumn x:Name="dgtcEditPackageProperties_Icon"/>
<sdk:DataGridTextColumn x:Name="dgtcEditPackageProperties_Entities" Header="AD Entities with Access" />
</sdk:DataGrid.Columns>
</sdk:DataGrid>
</StackPanel>
代碼背後:
public partial class MainPage : UserControl
{
private IList<string> myDataList = null;
string currentItemText;
public IList<string> Items
{
get;
private set;
}
public MainPage()
{
InitializeComponent();
Items = new List<string>();
Items.Add("One");
Items.Add("Two");
Items.Add("Three");
Items.Add("Four");
DataContext = this;
}
private void AddButton_Click(object sender, RoutedEventArgs e)
{
if (MyAutoCompleteBox.SelectedItem != null)
{
foreach (var item in MyAutoCompleteBox.SelectedItem)
{
ListBox.Items.Add(item);
myDataList.Remove(item);
}
ApplyDataBinding();
}
}
private void RemoveButton_Click(object sender, RoutedEventArgs e)
{
if (ListBox.SelectedItems != null)
{
int count = ListBox.SelectedItems.Count - 1;
for (int i = count; i >= 0; i--)
{
//myDataList.Add(ListBox.SelectedItems[i]);
ListBox.Items.Remove(ListBox.SelectedItems[i]);
}
ApplyDataBinding();
}
}
private void ApplyDataBinding()
{
MyAutoCompleteBox.ItemsSource = null;
MyAutoCompleteBox.ItemsSource = myDataList;
}
}
謝謝你的想法。是的,我沒有創建myDataList。我修改了代碼並將其留下。我會嘗試改變爲可觀察的收集。希望我能使它工作。 – vladc77 2011-03-07 23:03:14
我想知道你是否可以指點我的任何工作示例。我有麻煩讓它工作。再次感謝你。 – vladc77 2011-03-08 06:08:52