我試圖將一個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}" />
我看到的是,TESTBOX顯示編曲的第一個值在創建時。 但它並不反映對此元素的任何更改。 爲了在我的文本框中看到對Arr [0]的更改,我需要做些什麼?
但它不應該工作嗎?當值被替換時,ObservableCollection會引發一個CollectionChanged事件......我很驚訝綁定沒有注意到這一點。 – 2011-03-24 07:52:22
那麼,你綁定到元素,而不是集合,所以我猜UI只會監聽PropertyChanged事件 – ChrisWue 2011-03-24 07:58:55
如果我不想將元素索引(0)綁定到另一個控件,該怎麼辦? 例如我有一個ComboBox來選擇我的testBox應該顯示的元素的索引。 – MTR 2011-03-24 13:01:57