TRS
TRS

Reputation: 2097

Why converter is not getting called

I have converter to change my collection to list of values and their type.My converter accepts a class type and returns an IEnumerable

<ListView ItemsSource="{Binding Model,Converter={StaticResource PropConverter}}"/>

my partial class code is

  public partial class MainWindow : Window
{
    public Model Model
    {
        get;
        set;
    }


    public MainWindow()
    {
        Model=new Model();

        InitializeComponent();
    }
} 

where as if I change my code and xaml like this it calls the convereter

  public MainWindow()
    {
        DataContext=new Model();

        InitializeComponent();
    }

 <ListView ItemsSource="{Binding Converter={StaticResource PropConverter}}"/>

Can you please tell me the reason why this is happening.I prefer to do the first way but somehow it does not call converter.

Upvotes: 1

Views: 90

Answers (1)

kmatyaszek
kmatyaszek

Reputation: 19296

In first example:

It's not working because you don't assign DataContext so it's equal to null.

You can fix it by assign to DataContext value:

public partial class MainWindow : Window
{
    public Model Model
    {
        get;
        set;
    }

    public MainWindow()
    {
        Model=new Model();

        InitializeComponent();

        this.DataContext = this;
    }
} 

And now below binding will be working:

<ListView ItemsSource="{Binding Model,Converter={StaticResource PropConverter}}"/>

The better option is learning MVVM pattern and assign to DataContext ViewModel:

public class MainViewModel
{
    public MainViewModel()
    {
        Model = new Model();
    }
    public Model Model
    {
        get;
        set;
    }
}

View:

public partial class MainWindow : Window
{
    MainViewModel _vm;

    public MainWindow()
    {
        InitializeComponent();

        _vm = new MainViewModel();
        this.DataContext = _vm;
    }
} 

Upvotes: 1

Related Questions