.net 绑定到数组元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5415858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 15:23:49  来源:igfitidea点击:

Binding to an array element

.netwpfxamldata-binding

提问by MTR

I'm trying to bind a TextBlock to a specific element in an ObservableCollection. This is what I do right now:

我正在尝试将 TextBlock 绑定到 ObservableCollection 中的特定元素。这就是我现在所做的:

private ObservableCollection<double> arr = new ObservableCollection<double>();
public ObservableCollection<double> Arr { get { return arr; } set { arr = value; }  }

testBox.DataContext = this;

private void Button_Click(object sender, RoutedEventArgs e)
{
   Arr[0] += 1.0;
}

    [ValueConversion(typeof(ObservableCollection<double>), typeof(String))]
    public class myObsCollConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            ObservableCollection<double> l = value as ObservableCollection<double>;
            if( l == null )
                return DependencyProperty.UnsetValue;
            int i = int.Parse(parameter.ToString());

            return l[i].ToString();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }


    <Window.Resources>
        <local:myObsCollConverter x:Key="myConverter"/>
    </Window.Resources>

        <TextBlock Name="testBox" Text="{Binding Path=Arr,Converter={StaticResource myConverter}, ConverterParameter=0}" />

What I see is that testBox shows the first value of Arr when it is created. But it doesn't reflect any changes to this element. What do I have to do in order to see changes to Arr[0] in my textBox?

我看到的是 testBox 在创建时显示了 Arr 的第一个值。但它并不反映对此元素的任何更改。我必须做什么才能在我的文本框中看到对 Arr[0] 的更改?

回答by ChrisWue

No need for the converter. You can bind directly to Arr[0]like this

不需要转换器。你可以Arr[0]像这样直接绑定

 <TextBlock Name="testBox" Text="{Binding Path=Arr[0]}"/>

The elements in Arrwould need to implement INotifyPropertyChangedthough in order to dynamically update.

中的元素Arr需要实现INotifyPropertyChanged才能动态更新。

Update: To elaborate a bit more:

更新:详细说明一下:

public class MyDouble : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private double _Value;
    public double Value 
    { 
        get { return _Value; } 
        set { _Value = value; OnPropertyChanged("Value"); }
    }

    void OnPropertyChanged(string propertyName)
    {
       var handler = PropertyChanged;
       if (handler != null)
       {
          handler(this, new PropertyChangedEventArgs(propertyName));
       }
    }
}

and then

进而

 ObservableCollection<MyDouble> Arr { get; set; }

and bind to

并绑定到

 <TextBlock Name="testBox" Text="{Binding Path=Arr[0].Value}"/>

回答by OJ.

ObservableCollections do not propagate changes to values stored within objects that belong to the collection. It only fires off the notifications when the content of the collection itself changes (ie. item added, removed, reordered). If you want to make it so that your UI updates when values within the collection changes then you'll have to wire that up yourself separately.

ObservableCollections 不会将更改传播到存储在属于该集合的对象中的值。它仅在集合本身的内容发生更改(即添加、删除、重新排序项目)时触发通知。如果你想让你的 UI 在集合中的值发生变化时更新,那么你必须单独连接它。

回答by luka

you can use this way in my case I want to binding the visibility from an boolean array: code behind:

在我的情况下,您可以使用这种方式我想绑定布尔数组的可见性:后面的代码:

using System.Windows;
public static readonly DependencyProperty ButtonVisibleProperty =
        DependencyProperty.Register("ButtonVisible", typeof(BindingList<Boolean>), typeof(BaseWindow), new PropertyMetadata(new BindingList<Boolean>()));
 public BindingList<Boolean> ButtonVisible 
    { 
        get { return (BindingList<Boolean>)GetValue(BaseWindow.ButtonVisibleProperty); }
        set 
        {
            SetValue(BaseWindow.ButtonVisibleProperty, value);
            OnPropertyChanged("ButtonVisible");  
        } 
    }

and in Xaml:

在 Xaml 中:

Visibility=""{Binding Path=ButtonVisible[0], RelativeSource={RelativeSource AncestorType={x:Type Window}}}"

beware! the ancestorType depend of your Ancestor in my case is a window

谨防!在我的情况下,您的祖先的祖先类型是一个窗口