Niall_R

Hi

Its as simple as the subject suggests... Here's my XAML

Code Snippet

<Window.Resources>
<ObjectDataProvider x:Key="dataObject" ObjectInstance="{x:Static local:Window1.MyDictionary}"/>
</Window.Resources>

<Grid>
<ListBox ItemsSource="{Binding Source={StaticResource dataObject}}" />
</Grid>


MyDictionary is a public static property.

I can bind to a Dictionary<String, String> but not a Dictionary<int, String>. I get the following exception:

'System.Windows.Data.BindingExpression' value cannot be assigned to property 'ItemsSource' of object 'System.Windows.Controls.ListBox'. The given key was not present in the dictionary. Error at object 'System.Windows.Data.Binding' in markup file 'BindingTest;component/window1.xaml' Line 23 Position 13.

Help much appreciated

Niall


Re: Windows Presentation Foundation (WPF) Can't Data Bind to Dictionary<int, String>

Niall_R

Is no-one else using a non-string key !




Re: Windows Presentation Foundation (WPF) Can't Data Bind to Dictionary<int, String>

lee d

I tried the following seems to work fine

<Window x:Class="WindowsApplication1.Window1"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="WindowsApplication1" Height="300" Width="300" DataContext="{Binding RelativeSource={RelativeSource Self}}"

>

<Grid>

<ListBox Name="list1" ItemsSource="{Binding Path=MyData}"></ListBox>

</Grid>

</Window>

public partial class Window1 : System.Windows.Window

{

private Dictionary<int,string> _data;

public Dictionary<int,string> MyData

{

get { return _data; }

set { _data = value; }

}

public Window1()

{

MyData = new Dictionary<int, string>();

for (int i = 0; i < 10; i++)

MyData.Add(i, "item.." + i.ToString());

InitializeComponent();

}

}






Re: Windows Presentation Foundation (WPF) Can't Data Bind to Dictionary<int, String>

Niall_R

It fails if you do this tho:

public class MyDictionary : Dictionary<int, String>
{
public MyDictionary()
{
this.Add(1, "IntKeyOne");
this.Add(2, "IntKeyTwo");
this.Add(3, "IntKeyThree");
this.Add(4, "IntKeyFour");
}
}


Why does this cause it to fail




Re: Windows Presentation Foundation (WPF) Can't Data Bind to Dictionary<int, String>

lee d

I think it is using some kind of converter

try giving a path also

<Window.Resources>

<ObjectDataProvider x:Key="odp1" ObjectInstance="{xTongue Tiedtatic local:Window1.MyNewData}"/>

</Window.Resources>

<Grid>

<ListBox Name="list1" ItemsSource="{Binding Source={StaticResource odp1}, Path=Values}"></ListBox>

</Grid>






Re: Windows Presentation Foundation (WPF) Can't Data Bind to Dictionary<int, String>

Niall_R

Yep that was it, that's got it working.

Thanks alot Lee.