2014-04-26 1 views
0

그래서 사용자가 양식의 왼쪽에있는 텍스트 상자에 일부 텍스트를 입력하고 내 데이터 원본에서 사용 가능한 항목을 필터링 할 수 있도록 프로젝트를 구축하려고합니다. 명부. 철학 WPF 매개 변수에 바인딩에

<Label Content="Enter item name below"></Label> 
<TextBox Name="SearchTermTextBox" TabIndex="0" Text="" /> 

은 내가 목록이 다음 문자열을 달리했다 항목을 필터링하는 컨버터를 사용하여 데이터 소스에 바인딩 할 수있는 인상이었다.

<ListBox DataContext="{Binding Colors}"> 
    <ListBox.ItemsSource> 
    <MultiBinding Converter="{StaticResource FilterTextValueConverter}" ConverterParameter="{Binding ElementName=SearchTermTextBox, Path=Text}" /> 
    </ListBox.ItemsSource> 
    <ListBox.ItemTemplate> 
     //etc... 
    </ListBox.ItemTemplate> 
</ListBox> 

그러나 종속성 속성을 사용하지 않는 한 변환기 매개 변수의 요소 이름에 바인딩 할 수 없습니다.

편집 :

public class FilterTextValueConverter : IValueConverter 
{ 

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     var trackedColors = value as List<Colors>; 
     if (trackedColors != null) 
      return (trackedColors).Where(item => item.ColorName.Contains(parameter.ToString())).ToList(); 

     return null; 
    } 

    public object ConvertBack(object value, Type targetTypes, object parameter, CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 


public class Colors 
{ 
    public String ColorName; 
    public String Description; 
} 

여기 내 접근 방식에 어떤 문제가 : 나는 위의 코드와 혼란을 만들었습니다으로보고, 여기에 내가 바인딩 할 노력하고있어 컨버터입니까? 분명히 WPF 신을 분노하게 만들고 있는데, 이것은 매우 간단한 작업이기 때문에 원칙적으로 거부 당하고 있습니다. 어떤 도움을 주시면 감사하겠습니다.

답변

2

변환기가있는 단순 바인딩이 여기에서 작동하므로 멀티 바인딩이 필요하지 않습니다.

<ListBox ItemsSource="{Binding Path=Text, ElementName=SearchTermTextBox, 
          Converter="{StaticResource FilterTextValueConverter}"> 
    ...... 
</ListBox> 

FilterTextValueConverterIValueConverter를 구현하고 가정, 당신은 방법을 변환에 전달 된 값의 텍스트에 액세스 할 수 있습니다.

public class FilterTextValueConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, 
          System.Globalization.CultureInfo culture) 
    { 
     string text = value.ToString(); // TEXT for textBox can be accessed here. 
     return new List<string>(); // Return filtered list from here. 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, 
           System.Globalization.CultureInfo culture) 
    { 
     return Binding.DoNothing; 
    } 
} 


당신이 컨버터 여러 바인딩을 전달하려는 경우

UPDATE는 바인딩 할 수 없습니다, 따라서 IMultiValueConverter 때문에 ConverterParameter 재산을 종속되지 않고 사용합니다.

XAML 내가 허용 대답을 게시 한 후에도이 문제를 조사하고 나를 위해 작업을 계속

public class FilterTextValueConverter : IMultiValueConverter 
{ 
    public object Convert(object[] values, Type targetType, object parameter, 
          System.Globalization.CultureInfo culture) 
    { 
     var trackedColors = values[0] as List<Colors>; 
     if (trackedColors != null && !String.IsNullOrEmpty(values[1].ToString())) 
      return (trackedColors).Where(item => 
        item.ColorName.Contains(values[1].ToString())).ToList(); 

     return null; 
    } 

    public object[] ConvertBack(object value, Type[] targetTypes, 
           object parameter, 
           System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 
+0

불행히도 ConverterParameter를 SearchTermTextBox에 바인딩해야하며 Visual Studio에서는이를 허용하지 않습니다.내 변환기는 목록 을 반환해야합니다. –

+0

나는 나의 상황을 더 잘 설명하기 위해 원본을 편집했다. 나는 멀티가 불필요하다는 데 동의한다. 그것은 단지 그것을 얻기위한 실험 일 뿐이다. –

+0

변환기 매개 변수를 바인딩 할 수 없습니다. 당신은'IMultiValueConverter'을 사용할 필요가 있습니다. 나는 그 대답을 업데이트했다. 도움이되는지 확인하십시오. –

0

<ListBox DataContext="{Binding Colors}"> 
    <ListBox.ItemsSource> 
     <MultiBinding Converter="{StaticResource FilterTextValueConverter}"> 
      <Binding/> 
      <Binding ElementName="SearchTermTextBox" Path="Text"/> 
     </MultiBinding> 
    </ListBox.ItemsSource> 
</ListBox> 

변환기. 내가 발견 한 것은 적절한 바인딩을 허용하기 위해 새로운 dependencyproperty를 얻으려는 컨트롤을 래핑하는 것이 상당히 사소한 작업이라는 것입니다.

조금 더 복잡에도 불구하고 변환기를 추가하는 것보다 훨씬 더 우아한 해결책처럼이 훨씬 나중에 그렇게 결정에 내 자신의 대답을 받아들이는되지 않지만이 (내 아마추어 의견으로는) 것 같다

주 이것은 바인딩에 대한 원래 질문이 아니라 텍스트 상자의 caretindex 속성에 대한 새로운 의존성을위한 것이지만 작동시키기 위해서는 약간의 스마트 한 이름 바꾸기가 필요합니다.).

public class TextBoxDependencyWrapper : TextBox 
    { 
     public static readonly DependencyProperty CaretIndexProperty = DependencyProperty.Register(
      "CaretIndex", typeof (int), typeof (TextBoxDependencyWrapper), new FrameworkPropertyMetadata(default(int), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, CaretIndexChanged)); 

     protected override void OnKeyUp(KeyEventArgs e) //Event that changes the property we're trying to track 
     { 
      base.OnKeyUp(e); 
      CaretIndex = base.CaretIndex; 
     } 

     protected override void OnKeyDown(KeyEventArgs e) //Event that changes the property we're trying to track 
     { 
      base.OnKeyDown(e); 
      CaretIndex = base.CaretIndex; 
     } 

     public new int CaretIndex 
     { 
      get { return (int) GetValue(CaretIndexProperty); } 
      set { SetValue(CaretIndexProperty, value); } 
     } 
    }