zniwalla
zniwalla

Reputation: 387

Retrieve properties/fields from binded objects in ListView, XAML

How do I retrieve the objects in an ObservableCollection which is binded to a ListView? I want to show the properties/fields of these objects in the ListView. I'm using a MVVM design. The ListView is right now showing the namespace of the objects binded, just to clarify that the binding works.

The XAML:

<Page
    x:Class="Test.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Test"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:vm="using:Test.ViewModels"
    mc:Ignorable="d" d:DataContext="{d:DesignInstance vm:TestViewModel}">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Width="400" Height="400">
        <Border BorderBrush="Gray" BorderThickness="2">
            <ListView x:Name="TestList" ItemsSource="{Binding TestClasses}" Foreground="Black" Height="300">
                <!-- Code to bind TestClasses properties/fields goes here -->
            </ListView>
        </Border>
    </Grid>
</Page>

The code behind:

 public sealed partial class MainPage : Page
    {
        private readonly TestViewModel _viewModel;
        public MainPage()
        {
            _viewModel = new TestViewModel();
            DataContext = _viewModel;
            InitializeComponent();
        }
    }

My ViewModel:

class TestViewModel : BaseViewModel
    {
        private ObservableCollection<TestClass> _testClasses;
        public ObservableCollection<TestClass> TestClasses
        {
            get { return _testClasses; }
            private set
            {
                _testClasses = value;
                OnPropertyChanged();
            }
        }

        public TestViewModel()
        {
            TestClasses = new ObservableCollection<TestClass> { new TestClass("test1,", 1), new TestClass("test2", 2) };
        }
    }

And finally the class of which I would like to show the properties/fields:

[Bindable]
public class TestClass
{
    public TestClass(String name, int id)
    {
        Name = name
        Id = id;
    }
    public String Name { get; set; }
    public int Id { get; set; }
}

I seriously can't figure out a nice way to do this (I'm not interested in binding every possible property/field in the ViewModel itself) - I hope you guys can help!

Upvotes: 0

Views: 616

Answers (1)

Depechie
Depechie

Reputation: 6142

What did you try? Because if you define an ItemTemplate for that ListView you just bind to those properties like this:

<ListView>
  <ListView.ItemTemplate>
    <DataTemplate>
      <TextBlock Text={"Binding Name, Mode=TwoWay"} />
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

Upvotes: 3

Related Questions