ListView 中的自定义 ListViewItem自定义、ListView、ListViewItem

2023-09-07 14:51:40 作者:冰是睡著的水

在 ListViewItem 中显示项目的可能方式 WPF

possible ways to show item in ListViewItem WPF

更新:

这是我需要添加到 ListView 的控件,在这里我只需要显示计算机名称,该项目仍应包含计算机地址

that's the control i need to add to the ListView, in here i only need to display the Computer Name, still the item should hold the Computer Address

稍后,我将需要 ListView 以及代表文件和文件夹的项目,这些项目将具有:名称、路径、大小、图标、IsFile 属性.

later, i will need ListView with Items that represent Files and Folders which will have : Name, Path, Size, Icon, IsFile properties.

所以这就是我现在正在处理的问题,我卡在 listView 中,当我切换到 WPF 时我没想到会发生这种情况

so this's what I'm dealing with right now, im stuck in listView which i didn't expect to happen when i switched to WPF

推荐答案

这是另一个例子:

<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; }
}

结果:

 
精彩推荐