2011-06-14 34 views
0
<DataTemplate> 
    <StackPanel Orientation="Vertical" Name="AddressStackPanel" > 
    <ComboBox Name="ComboBox" ItemsSource="{Binding Path=MatchedAddressList}" DisplayMemberPath="Address" SelectedIndex="0" SelectionChanged="ComboBox_SelectionChanged"/> 
    <TextBlock Name="InputtedAddress" Text="{Binding Path=InputtedAddress}" Foreground={Hopefully pass the UI element to the dataconverter } /> 
    </StackPanel> 
</DataTemplate> 

ComboBox具有地理數據庫匹配的地址,並且選擇得分最高的值。文本塊具有用於匹配的用戶輸入地址。如果地址相同,我希望前景爲綠色,否則爲紅色。我可以將整個UI元素傳遞給IValueConverter嗎?

我想也許我可以將整個TextBlock傳遞到dataconverter,獲得它的父StackPanel,獲得子0,投射到組合框中獲取第0個元素並進行比較,然後返回紅色或綠色。這是否可行?

否則,我想我必須遍歷視覺樹是一樣醜,我認爲

回答

2
<DataTemplate> 
    <StackPanel Orientation="Vertical" Name="AddressStackPanel" > 
     <ComboBox Name="ComboBox" 
        ItemsSource="{Binding Path=MatchedAddressList}" 
        DisplayMemberPath="Address" SelectedIndex="0" 
        SelectionChanged="ComboBox_SelectionChanged"/> 
     <TextBlock Name="InputtedAddress" Text="{Binding Path=InputtedAddress}" 
        Foreground={"Binding RelativeSource={x:Static RelativeSource.Self}, 
           Converter={x:StaticResource myConverter}}" /> 
    </StackPanel> 
</DataTemplate> 

是。見msdn article

1

您可以使用它的值是否相等的InputtedAddress並返回Brushes.GreenBrushes.Red相應轉換器結合到ComboBoxSelectedItem

棘手的部分是,上述轉換器需要跟蹤InputtedAdress莫名其妙;這是非常麻煩的,因爲我們不能使用ConverterParameter來綁定,所以我們需要一個有點涉及的轉換器。

另一方面,效果可以通過IMultiValueConverter更容易實現。例如:

<ComboBox Name="ComboBox" ItemsSource="{Binding Path=MatchedAddressList}" DisplayMemberPath="Address" SelectedIndex="0" SelectionChanged="ComboBox_SelectionChanged"/> 
<TextBlock Name="InputtedAddress" Text="{Binding Path=InputtedAddress}"> 
    <TextBlock.Foreground> 
     <MultiBinding Converter="{StaticResource equalityToBrushConverter}"> 
      <Binding ElementName="ComboBox" Path="SelectedItem" /> 
      <Binding Path="InputtedAddress" /> 
     </MultiBinding> 
    </TextBlock.Foreground> 
</TextBlock> 

你會再需要一個IMultiValueConverter到兩個輸入值轉換爲Brush。這很容易使用documentation提供的示例。

相關問題