我建议你使用一些DataBinding。使用索引,并用它同步两个列表......不是很方便。
我们可以认为您有与您的约会相关的对象。
所以我创建了一个类:
public class CustomDate
{
public string name { get; set; }
public string description { get; set; }
public CustomDate(string iName, string iDescription)
{
this.name = iName;
this.description = iDescription;
}
}
然后我使用ObservableCollection 来处理这些对象。它类似于List,但会非常流畅地处理元素的添加/删除。
public partial class MainWindow : Window
{
ObservableCollection<CustomDate> CallNameList = new ObservableCollection<CustomDate>();
public MainWindow()
{
InitializeComponent();
CallNameList.Add(new CustomDate("Date #1", "Description of first date"));
CallNameList.Add(new CustomDate("Date #2", "This is a fantastic date"));
CallNameList.Add(new CustomDate("Date #3", "It will rain today"));
MyList.DataContext = CallNameList;
}
private void Delete_Click_1(object sender, RoutedEventArgs e)
{
CallNameList.Remove((CustomDate)MyList.SelectedItem);
}
}
这里是 XAML/WPF 部分。您应该关注DataBinding 部分。如果你不熟悉它,你应该找到并阅读一些教程。没有 DataBinding 的 WPF 毫无意义。
<Window x:Class="StackTest.MainWindow"
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:local="clr-namespace:StackTest"
mc:Ignorable="d"
Title="Laser Control " Height="300" ResizeMode="CanMinimize" Cursor="Arrow" Width="400">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<ListBox Name="MyList" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Name="Delete" Click="Delete_Click_1" Grid.Row="1" Content="Delete current date"/>
</Grid>
<Grid Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" HorizontalAlignment="Center" Text="{Binding ElementName=MyList, Path=SelectedItem.name}"/>
<TextBlock Grid.Row="1" HorizontalAlignment="Center" Text="{Binding ElementName=MyList, Path=SelectedItem.description}"/>
</Grid>
</Grid>
</Window>
这种方式不是唯一的,但我觉得它非常方便,因为DataBinding 正在为我处理所有事情。而且很容易添加更多信息,或者修改 UI 而无需修改其背后的逻辑。