0

I'm having following classes:

class MyViewModel
{
    public List<MyItem> MyItems { get; set; }
    public int Width { get; set; }
}

class MyItem
{
    public string Name {get; set;}
}

As you see, there's a list of MyItems and Width property in the same class called MyViewModel. How can I bind a single element of that list to a Text property in XAML and Width from ViewModel to XAML's Width property? Here's my try, but I can't at the same time bind those two properties. I mean, I can bind whole list to Text property, but I don't know how could I bind a single item.

<ListView ItemsSource="{Binding MyViewModel}">
<ListView.ItemTemplate>
    <DataTemplate>
        <Grid Height="15" Width="520">
            <TextBlock Width="{Binding Width}" Text="{Binding=MyItems.Name(?)}" />
        </Grid>
    </DataTemplate>
</ListView.ItemTemplate>

MrCrow
  • 23
  • 4
  • use `MyItems` as `ItemsSource` (if MyViewModel is the DataContext of the ListView) and then bind `Text` to `Name` – Flat Eric Jun 26 '15 at 13:15
  • but then Width property is gone and I can't bind it, because only MyItems is an ItemsSource – MrCrow Jun 26 '15 at 13:20
  • You could use `RelativeSource` in the Binding – Flat Eric Jun 26 '15 at 13:22
  • Could you provide any example with RelativeSource? I have no idea how could I bind that. – MrCrow Jun 26 '15 at 14:08
  • Here is an example: http://stackoverflow.com/questions/84278/how-do-i-use-wpf-bindings-with-relativesource. Not sure if this works for windows-store-apps, I just know it from WPF – Flat Eric Jun 26 '15 at 14:12

1 Answers1

0

You should revise your design, but here is a quick fix: just introduce a readonly property, that returns the first element, so you will have this (assuming MyItems always has at least element, otherwise you will get an exception):

class MyViewModel
{
    public List<MyItem> MyItems { get; set; }

    public int Width { get; set; }

    public MyItem FirstElement { get { return MyItems[0]; } }
}

In your xaml you bind TextBlock to this property:

<ListView ItemsSource="{Binding MyViewModel}">
<ListView.ItemTemplate>
    <DataTemplate>
        <Grid Height="15" Width="520">
            <TextBlock Width="{Binding Width}" Text="{Binding=FirstElement}" />
        </Grid>
    </DataTemplate>
</ListView.ItemTemplate>

A little bit offtopic, but still important: viewmodel classes often implement INotifyPropertyChanged, so that views will be able to update themselves automatically. For the same reason List<T> should be replaced with ObservableCollection<T>.

Alex Sikilinda
  • 2,928
  • 18
  • 34
  • Unfortunately, there's a possibility that the list would be empty. Maybe your right, I should design the classes in different way, but still I'm surprised that there's no elegant solution to this. – MrCrow Jun 26 '15 at 14:10
  • So if `MyItems` is empty, what you want to display? – Alex Sikilinda Jun 26 '15 at 15:25