2011-03-24 7 views
11

ObservableCollection의 특정 요소에 TextBlock을 바인딩하려고합니다. 내가 볼 것은 만들 때 testBox는 ARR의 첫 번째 값을 보여주고 있다는 점이다배열 요소에 바인딩

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

: 이것은 내가 지금하는 일이다. 그러나이 요소에 대한 변경 사항은 반영되지 않습니다. 내 textBox에서 Arr [0] 변경 사항을 보려면 어떻게해야합니까?

답변

21

변환기가 필요 없습니다. 동적 업데이트하기 위해하지만 INotifyPropertyChanged을 구현해야 Arr

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

요소처럼 Arr[0]에 직접 바인딩 할 수 있습니다.

업데이트 : 당신은 내가 원하는 내 경우에는이 방법을 사용할 수 있습니다

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

그래도 어쨌든 작동하지 않아야합니까? ObservableCollection은 값이 대체 될 때 CollectionChanged 이벤트를 발생시킵니다 ... 바인딩이이를 인식하지 못함에 놀랍습니다. –

+0

글쎄, UI가 PropertyChanged 이벤트 만 듣기 때문에 컬렉션이 아닌 요소에 바인딩합니다. – ChrisWue

+0

요소 인덱스 (0)를 다른 컨트롤에 바인딩하지 않으면 어떻게됩니까? 예 : 필자는 testBox가 표시해야하는 요소의 색인을 선택하는 ComboBox를 가지고있다. – MTR

3

ObservableCollection s는 컬렉션에 속한 개체에 저장된 값에 변경 내용을 전파하지 않습니다. 컬렉션 자체의 내용이 변경되면 (예 : 항목 추가, 제거, 재정렬) 알림 만 실행됩니다. 컬렉션 내의 값이 바뀌면 UI가 업데이트되도록하려면 별도로 연결해야합니다.

+0

이것은 개체의 내부 데이터를 수정하지 않고 아이템을 대체하고 있습니다. 방금 체크했는데이 경우 CollectionChanged 이벤트가 발생합니다 (바꾸기 액션 사용). –

0

바인딩 : 좀 더 정교한하려면 부울 배열에서 가시성을 바인딩하는 방법 :뒤에코드 :

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

및 XAML에서 :

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

조심! ancestorType 내 조상의 조상은 창입니다.

관련 문제