3

possible ways to show item in ListViewItem WPF

Update: enter image description here

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

enter image description here

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

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

Murhaf Sousli
  • 12,622
  • 20
  • 119
  • 185
  • [XY Problem](http://meta.stackexchange.com/a/66378). What do you want that for? Use a regular `ListViewItem`. – Federico Berasategui Dec 11 '13 at 21:13
  • I'm sorry, you have no idea what you're talking about. What are you trying to do? BTW, **Don't manipulate UI elements in procedural code in WPF, that's what XAML is for**. – Federico Berasategui Dec 11 '13 at 21:28
  • @HighCore if you think so, I'm working on `listView` as file Explorer, and `listViewItem` as a File item, I need to add Name,Size,Path,IsFile,Image to each item, and that makes it more complicated than creating a `userControl` which only misses `IsSelected` property! so what do you think? – Murhaf Sousli Dec 11 '13 at 21:34
  • Just add additional Columns to the GridView. I don't see what the big difficulty is – Federico Berasategui Dec 11 '13 at 21:35
  • @HighCore You don't get it, I've already been threw all that, and when i get it done with `ListViewItem` and i override it to add more properties, but my problem was that i couldn't be able to assign the extra properties to my custom `ListViewItem Style`. There are no much articles and questions about it, and everyone is using more complex way than the other. I believe using `userControl` is more suitable for this case. – Murhaf Sousli Dec 11 '13 at 21:45
  • I am with HighCore. What do you need that a GridView with a checkbox column bound to a property IsSelected would not do? – paparazzo Dec 11 '13 at 21:48
  • @MurHaf `You don't get it` - Yes I get it perfectly. You're trying to use WPF as if it were winforms. **IT IS NOT**. Learn WPF properly and forget winforms. – Federico Berasategui Dec 11 '13 at 21:48
  • @HighCore alright let it be `ListViewItem`, what about adding new properties which are not existed in regular `listViewItem`, do you have a solution? – Murhaf Sousli Dec 11 '13 at 21:56
  • It's called 'Attached Property'. You can read about if you ever decide to take up WPF – Gayot Fow Dec 11 '13 at 21:58
  • @Blam `ListViewItem` Already have `IsSelected` property, why would i need a checkbox column for! – Murhaf Sousli Dec 11 '13 at 21:59
  • @MurHaf You DONT NEED to add properties in the UI to hold Data. UI is not Data. Please learn that. Please post a screenshot of what you need so we can tell you the proper way to do it in WPF. – Federico Berasategui Dec 11 '13 at 21:59
  • @HighCore here you go – Murhaf Sousli Dec 11 '13 at 22:15

2 Answers2

11

Here is another example:

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

Code Behind:

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

Data Item:

public class ComputerInfo
{
    public string Name { get; set; }
    public string Ip { get; set; }
}

Result:

enter image description here

Federico Berasategui
  • 43,562
  • 11
  • 100
  • 154
6

Look dude, I made a simple "File Explorer" example in a couple of lines of XAML in 5 minutes.

There is NO need to create your own ListViewItem or anything like that. WPF is NOT winforms. You need to understand this.

I already explained this to you. UI is Not Data.

Look:

<Window x:Class="WpfApplication14.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication14"
        Title="MainWindow" Height="350" Width="525">
    <ListView ItemsSource="{Binding}">
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="IsSelected" Value="{Binding IsSelected}"/>
            </Style>
        </ListView.ItemContainerStyle>

        <ListView.View>
            <GridView>
                <GridViewColumn>
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox IsChecked="{Binding IsSelected}"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
                <GridViewColumn Header="Size">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock x:Name="Size" Text="{Binding Size}"/>
                            <DataTemplate.Triggers>
                                <DataTrigger Binding="{Binding IsFile}" Value="False">
                                    <Setter TargetName="Size" Property="Text" Value="[Directory]"/>
                                </DataTrigger>
                            </DataTemplate.Triggers>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="Path" DisplayMemberBinding="{Binding Path}"/>
            </GridView>
        </ListView.View>
    </ListView>
</Window>

Code Behind:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        var path = @"C:\";

        var dirs = Directory.GetDirectories(path)
                            .Select(x => new DirectoryInfo(x))
                            .Select(x => new FileViewModel()
                            {
                                Name = x.Name,
                                Path = x.FullName,
                                IsFile = false,

                            });

        var files = Directory.GetFiles(path)
                               .Select(x => new FileInfo(x))
                               .Select(x => new FileViewModel()
                               {
                                   Name = x.Name,
                                   Path = x.FullName,
                                   Size = x.Length,
                                   IsFile = true,
                               });


       DataContext = dirs.Concat(files).ToList();

    }
}

Data Item:

public class FileViewModel: INotifyPropertyChanged
{
    private bool _isSelected;
    public bool IsSelected
    {
        get { return _isSelected; }
        set
        {
            _isSelected = value;
            OnPropertyChanged("IsSelected");
        }
    }

    public string Name { get; set; }
    public long Size { get; set; }
    public string Path { get; set; }
    public bool IsFile { get; set; }
    public ImageSource Image { get; set; }
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

Result:

enter image description here

Do you see? There is no need to overcomplicate anything. WPF has everything you need to do anything.

Community
  • 1
  • 1
Federico Berasategui
  • 43,562
  • 11
  • 100
  • 154