WPF 中的字典失败绑定



我的应用程序中的大部分文本块和单选按钮对象都绑定到我的字典

我将新值存储在字典中。

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

下面是一个示例:(此代码运行正常,如果在开始应用中找不到匹配项,它只会很慢。

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

当我尝试启动应用程序并且绑定尝试查找 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)'

有没有办法使连接在字典为空时不引发异常

您还可以使用空值初始化字典,然后将绑定模式设置为 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>

解决此问题的一种方法是覆盖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 添加到字典中。

我使用你的类自定义词典

这是我的 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

在你的类 自定义词典 在

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

最新更新