更新时间:2021-12-01 03:19:52
这是另一个例子:
<Window x:Class="WpfApplication14.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<DockPanel>
<Button Content="Show Selected Computer" Click="Button_Click" DockPanel.Dock="Top"/>
<ListBox ItemsSource="{Binding}"
SelectedItem="{Binding SelectedComputer, RelativeSource={RelativeSource AncestorType=Window}}">
<ListBox.ItemTemplate>
<DataTemplate>
<DockPanel Margin="2">
<Rectangle Fill="Gray" Width="32" Height="32" DockPanel.Dock="Left"/>
<TextBlock Text="{Binding Name}" VerticalAlignment="Center"/>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DockPanel>
</Window>
代码背后:
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
DataContext = Enumerable.Range(1,10)
.Select(x => new ComputerInfo()
{
Name = "Computer" + x.ToString(),
Ip = "192.168.1." + x.ToString()
});
}
public ComputerInfo SelectedComputer { get; set; }
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(SelectedComputer.Ip);
}
}
数据项:
public class ComputerInfo
{
public string Name { get; set; }
public string Ip { get; set; }
}
结果: