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 具有与所选得分值最高的地理数据库匹配的地址。文本块具有用于匹配的用户输入地址。如果地址相同,我希望前景为绿色,否则为红色。

我想也许我可以将整个 TextBlock 传递给数据转换器,获取其父 StackPanel,获取子 0,转换为 Combobox 获取第 0 个元素并进行比较,然后返回红色或绿色。这是可行的吗?

否则我想我必须遍历我认为丑陋的视觉树

4

2 回答 2

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文章

于 2011-06-14T21:34:45.333 回答
1

您可以使用一个转换器将其绑定到SelectedItem,该ComboBox转换器将其值与 进行比较,InputtedAddress并相应地返回Brushes.GreenBrushes.Red

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>

然后,您需要 aIMultiValueConverter将两个传入值转换为 a Brush使用文档提供的示例很容易做到这一点。

于 2011-06-14T21:41:07.637 回答