WPF 更新绑定到数组中的元素 [英] WPF update binding to element in an array

查看:24
本文介绍了WPF 更新绑定到数组中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经仔细搜索过了,很可能我遗漏了一些重要且明显的东西.

I've searched my little heart out and its entirely possible that I'm missing something critical and obvious.

我有一个 BitArray 和一系列绑定到数组元素的复选框,如下所示:

I have a BitArray and a series of checkboxes that are bound to elements in the array, like so:

<CheckBox IsChecked="{Binding Permissions[0]}" />
<CheckBox IsChecked="{Binding Permissions[1]}" />
...
<CheckBox IsChecked="{Binding Permissions[5]}" />

他们正确地从该属性中获取其值,但更改复选框似乎不会触发该属性的设置器.

They get their values from that property correctly, but changing the checkboxes doesn't seem to trigger that property's setter.

我尝试了一个非常简单的示例,其中单个 TextBox 绑定到字符串数组的一个元素.

I tried a really simple example with a single TextBox bound to an element of a string array.

class TestArray
{
    private string[] _nameArray = new string[3];

    public TestArray()
    {
        _nameArray[1] = "test name";
    }

    public string[] NameArray
    {
        get { return _nameArray; }
        set { _nameArray = value; }
    }
}

这是 UI 元素:

<TextBox Text="{Binding NameArray[1], UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />

同样,这个 TextBox 从绑定中获取名称就好了,但如果我改变它就不会命中 setter.

Again, this TextBox gets the name from the binding just fine, but doesn't hit the setter if I change it.

这完全是一个愚蠢的问题,可能源于严重缺乏理解,所以感谢您的耐心等待!

This could totally be a bonehead question and may stem from a serious lack of understanding so thanks for your patience!

推荐答案

同样,这个 TextBox 从绑定中获取名称就好了,但如果我改变它就不会命中 setter.

Again, this TextBox gets the name from the binding just fine, but doesn't hit the setter if I change it.

它不需要调用setter:绑定不会替换数组,它只是替换数组的一个元素.如果您检查数组中的值,您将看到它们反映了更改.

It doesn't need to call the setter: the binding doesn't replace the array, it simply replaces an element of the array. If you check the values in the array, you will see that they reflect the changes.

它也适用于 BitArray(我只是尝试使用数组和 BitArray).

It also works fine with a BitArray (I just tried with both an array and a BitArray).

但是,数组(和 BitArray)不实现 INotifyPropertyChangedINotifyCollectionChanged,因此如果数组中的值有其他绑定,它们将不会自动刷新.您将需要一个实现这些接口的包装器(例如 ObservableCollection)

However, arrays (and BitArray) don't implement INotifyPropertyChanged or INotifyCollectionChanged, so if there are other bindings to the values in the array, they won't be refreshed automatically. You will need a wrapper that implements these interfaces (ObservableCollection<T> for instance)

这篇关于WPF 更新绑定到数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆