metacircle
metacircle

Reputation: 2588

WPF MVVM DataTemplate Binding

In my View I am showing a list of Items, one of which is the currently active item. For these items I defined a Datatemplate. The currently active item is exposed as a property on the ViewModel.

I want to show the currently active item with a different background color, so I tried to create an IValueConverter and Bind the Converter Parameter to the current item, compare it with the running Item and return the corresponding Brush. But since it is not possible to Bind a converters parameter I failed.

I don't want to add a propery to my Item class (e.g. bool IsActive), since this doesn't really belong to my data model.

Any ideas how to achieve the result I am looking for?

ViewModel:

public ObservableCollection<Item> Items {get;set;}
public Item ActiveItem {get; set;}

View:

<DataTemplate DataType="{x:Type model:Item}">
            <Border Margin="3"
                    BorderBrush="DimGray"
                    BorderThickness="1"
                    CornerRadius="2"
                    Padding="3"
                    Background={Binding ???}
                    >
...
</DataTemplate>

Upvotes: 0

Views: 356

Answers (1)

Niels
Niels

Reputation: 620

Your data model is something, your ViewModel can be different, it's exactly for that :). I like to use a decorator pattern to add that type of property to my business object.

public class Decorator<T> : INotifyPropertyChanged
{
   public T MyObject { get; set; }
   ...

   public bool IsActive { get; set; }

}

and if you need many new properties in your ViewModel classes, create some MyItemViewModel classes can be useful too.

ViewModel are not only for your View but to manage how your business object are displayed, don't be afraid to create new classes around that.

Upvotes: 3

Related Questions