绑定到一个数组元素数组、绑定、元素

2023-09-03 16:11:20 作者:喜欢别告白〃直接吻

我试图绑定一个TextBlock到一个特定的元素在一个ObservableCollection。 这就是我现在做:

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

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}" />

我看到的是,TESTBOX显示编曲的第一个值在创建时。 不过,这并不反映任何改变这个元素。 什么是我必须做才能看到变化ARR [0]我的textBox?

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?

推荐答案

无需转换。您可以直接绑定到编曲[0] 像这样

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

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

编曲元素需要实现 INotifyPropertyChanged的虽然以动态更新。

The elements in Arr would need to implement INotifyPropertyChanged though in order to dynamically update.

更新:为了详细一​​点:

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

然后

 ObservableCollection<MyDouble> Arr { get; set; }

和绑定到

 <TextBlock Name="testBox" Text="{Binding Path=Arr[0].Value}"/>
 
精彩推荐
图片推荐