forum

Home / DeveloperSection / Forums / Dictionary Failure binding in WPF

Dictionary Failure binding in WPF

Anonymous User 5851 10-Apr-2014

I have most of the textblock and radio button objects in my app bound to my dictionnary

I store the new value in a Dictionary.

The problem is that the binding failure is throwing an exception that is very slow.

Here is an example: (this code runs correctly, it is just slow if it can't find a match in the start app.)

<StackPanel>
    <TextBox Text="{Binding Dictio[0], Mode=TwoWay}"/>
    <TextBox Text="{Binding Dictio[1], Mode=TwoWay}"/>
    <RadioButton GroupName="select" IsChecked="{Binding Dictio[2], Mode=TwoWay}" Content="true"/>
</stackPanel>

And in my class

    private Dictionary<int, object> _Dictio;
 public MainWindow()
        {
            Dictio = new Dictionary<int, object>();
            this.DataContext = this;
            InitializeComponent();
        }
public Dictionary<int, object> Dictio
        {
            get { return _Dictio; }
            set { _Dictio = value; }
        }
private void test(object sender, RoutedEventArgs e)
{
    foreach (KeyValuePair<int, object> kvp in Dictio)
            {
                Console.Out.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
        }
}

When I try to start app and the binding tries to lookup Dictio[key], I get this in my output window for all the key of my dictionnary Dictio:

 System.Windows.Data Error: 17 : Cannot get 'Item[]' value (type 'Object') from 'Dictio' (type 'Dictionary`2'). BindingExpression:Path=Dictio[4]; DataItem='MainWindow' (Name=''); target element is 'RadioButton' (Name='mm'); target property is 'IsChecked' (type 'Nullable`1') TargetInvocationException:'System.Reflection.TargetInvocationException: Une exception a été levée par la cible d'un appel. ---> System.Collections.Generic.KeyNotFoundException: La clé donnée était absente du dictionnaire.

System.Collections.Generic.Dictionary`2.get_Item(TKey key)

  --- Fin de la trace de la pile d'exception interne ---

 System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)

System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)

 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)

 System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)

 MS.Internal.Data.PropertyPathWorker.GetValue(Object item, Int32 level)

 MS.Internal.Data.PropertyPathWorker.RawValue(Int32 k)'

Is there a way to make the connection not throw an exception if the dictionary is empty?


wpf wpf 
Updated on 11-Apr-2014
I am a content writter !

Can you answer this question?


Answer

1 Answers

Liked By