2010-05-26 111 views
0

我有XAML与此类似:从ComboBox的孩子里面访问父级控制控制

<ListBox ItemsSource="{Binding SearchCriteria, Source={StaticResource model}}" SelectionChanged="cboSearchCriterionType_SelectionChanged"> 
<ListBox.ItemTemplate> 
    <DataTemplate> 
     <StackPanel Name="spCriterion" Orientation="Horizontal" Height="20"> 
      <ComboBox Name="cboSearchCriterionType" Width="120" SelectionChanged="cboSearchCriterionType_SelectionChanged"> 
       <ComboBox.Items> 
        <ComboBoxItem IsSelected="True" Content="Anagram Match" /> 
        <ComboBoxItem Content="Pattern Match" /> 
        <ComboBoxItem Content="Subanagram Match" /> 
        <ComboBoxItem Content="Length" /> 
        <ComboBoxItem Content="Number of Vowels" /> 
        <ComboBoxItem Content="Number of Anagrams" /> 
        <ComboBoxItem Content="Number of Unique Letters" /> 
       </ComboBox.Items> 
      </ComboBox> 
      <TextBox x:Name="SearchSpec" Text="{Binding SearchSpec}" /> 
      <TextBox x:Name="MinValue" Text="{Binding MinValue}" Visibility="Collapsed" /> 
      <TextBox x:Name="MaxValue" Text="{Binding MaxValue}" Visibility="Collapsed" /> 
     </StackPanel> 
    </DataTemplate> 
</ListBox.ItemTemplate> 

你可以从标记告诉,我有一个绑定到一个集合列表框SearchCriterion对象(共同包含在SearchCriteria对象中)。这个想法是用户可以从标准添加/删除标准项目,每个标准由一个列表框项目表示。在列表框项目中,我有一个组合框和三个文本框。我想要做的是根据在ComboBox中选择的项目来更改TextBox控件的可见性。例如,如果用户选择“模式匹配”,那么我只想显示第一个文本框并隐藏后两个;相反,如果用户选择“长度”或任何“数量...”项目,那么我想隐藏第一个文本框并显示后两个。

达到此目的的最佳方法是什么?我希望在组合框的SelectionChanged事件处理程序中做一些简单的事情,但是文本框控件大概不在组合框的SelectionChanged事件范围内。我是否必须以编程方式遍历控件层次结构并找到控件?

回答

0

您可以将可见性绑定到组合框选定项目,然后使用值转换器返回可见性。 here is a demo of how to do Binding Converters这可能会帮助你。

<TextBox x:Name="MinValue" Text="{Binding MinValue}" Visibility="{Binding SelectedItem, ElementName=cboSearchCriterionType, Converter={StaticResource MyConverter}}" /> 

// declare the converter in xaml.... 
<SomeElement.Resource> 
<local:MyConverter x:Key="MyConverter"/> 
</SomeElement.Resource> 

public class MyConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     // value will be the combobox.selecteditem 
     // do stuff and return the visibility 
    } 
} 
+0

谢谢,这个工作。我不得不创建两个ValueConverter类:一个用于搜索规范文本框,另一个用于最小/最大文本框。我没有看到一个方法来创建一个ValueConverter类所有三个文本框,因为我看不到的方式进行转换的方法来知道谁在调用它。 – eponymous23 2010-05-27 18:29:56