WPF中的字典失败绑定

时间:2014-02-20 10:15:08

标签: c# wpf dictionary binding

我的应用程序中的大多数textblock和单选按钮对象都绑定到了我的词典

我将新值存储在Dictionary中。

问题是绑定失败会引发一个非常慢的异常。

以下是一个示例:(此代码运行正常,如果在启动应用中找不到匹配项,则速度很慢。)

<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>

在我班上

    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);
        }
}

当我尝试启动app并且绑定尝试查找Dictio [key]时,我在输出窗口中获取了我的词典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)'

如果字典为空,是否有办法使连接不引发异常

3 个答案:

答案 0 :(得分:0)

解决此问题的一种方法是覆盖Dictionary<int, object>

public class CustomDictionary : IEnumerable
{
    private Dictionary<int, Tuple<DependencyObject, DependencyProperty>> properties = new Dictionary<int, Tuple<DependencyObject, DependencyProperty>>();

    IEnumerator IEnumerable.GetEnumerator()
    {
        foreach (var item in properties)
        {
            yield return  new KeyValuePair<int, object>(item.Key, item.Value.Item1.GetValue(item.Value.Item2));
        }
    }

    public void Add(int index, DependencyObject obj, DependencyProperty property)
    {
        properties.Add(index, new Tuple<DependencyObject, DependencyProperty>(obj, property));
    }

    public object this[int index]
    {
        get
        {
            return properties[index].Item1.GetValue(properties[index].Item2);
        }
        set
        {
            properties[index].Item1.SetCurrentValue(properties[index].Item2, value);
        }
    }
}

然后,不要在任何地方使用Dictionary,而是使用CustomDictionary,如下所示:

private CustomDictionary _Dictio;

public CustomDictionary Dictio
{
    get { return _Dictio; }
    set { _Dictio = value; }
}

同样在您的MainWindow中,您必须在调用InitializeComponent()之后初始化Dictio,如下所示:

public MainWindow()
{
    InitializeComponent();

    Dictio = new CustomDictionary();
    Dictio.Add(0, textBox1, TextBox.TextProperty);
    Dictio.Add(1, textBox2, TextBox.TextProperty);
    Dictio.Add(2, radioButton, RadioButton.IsCheckedProperty );

    this.DataContext = this;
}

这会将DependencyObjects的实例和要绑定的相应DependencyProperty添加到字典中。

答案 1 :(得分:0)

我使用你的CustomDictionary类

这是我的xaml文件

<StackPanel>
    <TextBox Name="textBox1" Text="{Binding Dictio[0], Mode=TwoWay}"/>
    <TextBox Name="textBox2" Text="{Binding Dictio[1], Mode=TwoWay}"/>
    <RadioButton Name="radioButton" GroupName="select" IsChecked="{Binding Dictio[2], Mode=TwoWay}" Content="true"/>
<Button Content="test" Click="test"/>
</StackPanel>

在我班上

    private CustomDictionary _Dictio;

 public MainWindow()
        {
            Dictio = new CustomDictionary();
            this.DataContext = this;
            InitializeComponent();
        }

    public CustomDictionary 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);
            }
    }

当我执行时我有这个错误

Une exception de première chance de type 'System.Collections.Generic.KeyNotFoundException' s'est produite dans mscorlib.dll

中的类CustomDictionnary中

 return properties[index].Item1.GetValue(properties[index].Item2);

答案 2 :(得分:0)

您也可以使用空值初始化字典,然后将绑定模式设置为OneWayToSource,如下所示:

public MainWindow()
{
    Dictio = new Dictionary<int, object>();
    for (int i = 0; i < 200; i++)
    {
        Dictio.Add(i, new object());
    }
    InitializeComponent();
    this.DataContext = this;
}

<StackPanel>
    <TextBox Text="{Binding Dictio[0], Mode=OneWayToSource}"/>
    <TextBox Text="{Binding Dictio[1], Mode=OneWayToSource}"/>
</StackPanel>