Question

So I have aproblem with binding in WPF. I am trying to bind a DataGrid ComboBoxColumn with a static resource but with no luck. I know where the problem is but I'm not sure how to fix it.

in XAML i have this:

<local:MyClasificators x:Key="clList"></local:MyClasificators>

and DataGridComboBoxColumn

<DataTemplate>
    <ComboBox ItemsSource="{StaticResource clList}" DisplayMemberPath="Value"  ></ComboBox>
</DataTemplate>

code for the source I'm binding:

public class MyClasificators:List<KeyValuePair<object, object>>
{
    public void _MyClasificators(DataTable country)
    {
        foreach (DataRow row in country.Rows)
        {
            this.Add(new KeyValuePair<object, object>(row.ItemArray[0], row.ItemArray[1]));
        }
    }

And the code for passing the DataTable:

public void callMyClassificators(DataTable country)
{
    MyClasificators clasif = new MyClasificators();
    clasif._MyClasificators(country);
}

I know that most probably I just have to edit the Resource part, but I'm not sure how should I go about it?

Was it helpful?

Solution

<local:MyClasificators x:Key="clList"></local:MyClasificators>

translates to something like:

Resources.Add("clList", new MyClasificators());

That's it, there's no data in your object.

You could create the resource clList from code, for example in app.xaml.cs:

var countryTable = ... // Get or create table here
var clList = new MyClasificators();
var clList.callMyClassificators(countryTable);
Resources.Add("clList", clList);

OTHER TIPS

From above code, it seems that an instance of MyClasificators is created in resource section. But MyClasificators (clList) does not have any items. It's an empty list. Place a break point in your code and check this.Resources["clList"] and check the count of items in it.

I see multiple problems.

  1. in callMyClassificators, you create a new instance of MyClasificators. That instance is not the one you bind in Xaml. When you define a local resource, one instance is created there. That's the one your Combox is bound to, not the one you create in callMyClassificators. You should make sure xaml and code work on the same instance.

  2. Let's say you fix No.1. When is "callMyClassificators" called? After the binding is done, there is no way for your MyClasificators to notify WPF that the list has changed. You could use a ObservableCollection> so that collection change will automatically be observed by WPF.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top