2012-09-20 44 views

回答

1

这里是解决方案的演示:https://dl.dropbox.com/u/8424800/StackOverflowSl.html(见组合框筛选)

我把默认的Silverlight组合框模板,并增加了一个“FilterTextBox”的弹出部分。因为它超出了StackOverflow的限制,所以我无法发布整个xaml。全部来源是here as a GitHub Gist。我已经离开了重要的部分。接下来,TextBox上的事件处理程序需要连接起来。

<Style TargetType="ComboBox"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="ComboBox"> 
       <Grid>      
        <Popup x:Name="Popup"> 
         <Border x:Name="PopupBorder" 
           Height="Auto" 
           HorizontalAlignment="Stretch" 
           BorderBrush="{TemplateBinding BorderBrush}" 
           BorderThickness="{TemplateBinding BorderThickness}" 
           CornerRadius="3"> 
          <Border.Background> 
           <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1"> 
            <GradientStop Offset="0" Color="#FFFFFFFF" /> 
            <GradientStop Offset="1" Color="#FFFEFEFE" /> 
           </LinearGradientBrush> 
          </Border.Background> 
          <Grid> 
           <TextBox x:Name="FilterTextBox" 
              Height="22" 
              VerticalAlignment="Top" /> 
           <ScrollViewer x:Name="ScrollViewer" 
               Margin="0,25,0,0" 
               BorderThickness="0" 
               Padding="1"> 
            <ItemsPresenter /> 
           </ScrollViewer> 
          </Grid> 
         </Border> 
        </Popup> 
       </Grid> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

接线,文本框

public Q12513294() 
{ 
    // Required to initialize variables 
    InitializeComponent(); 

    InitializeMyCombo(
     Enumerable.Range(1, 99).Select(x => "Beer " + x.ToString() + " on the wall"), 
     (object item, string filter) => (item as String).Contains(filter) 
    ); 
} 

private void InitializeMyCombo(IEnumerable items, Func<object, string, bool> filter) 
{ 
    MyComboBox.Loaded += (s, e) => 
    { 
     // PagedCollectionView implements a filterable collection 
     PagedCollectionView list = new PagedCollectionView(items); 
     MyComboBox.ItemsSource = list; 

     // Set the filter based on the contents of the textbox 
     TextBox filterTextBox = MyComboBox.GetTemplateChild<TextBox>("FilterTextBox"); 
     list.Filter = new Predicate<object>(
      item => filter(item, filterTextBox.Text) 
      ); 

     // Refresh the filter each time 
     filterTextBox.TextChanged += (s2, e2) => 
     { 
      list.Refresh(); 
      filterTextBox.Focus(); 
     }; 
    }; 

} 

public static class Helper 
{ 
    public static T GetTemplateChild<T>(this DependencyObject parent, string partName) 
    { 
     return (T)(VisualTreeHelper.GetChild(parent, 0) as Panel).FindName(partName); 
    } 
}