Can I pass entire UI element into a IValueConverter?

扶醉桌前 提交于 2019-11-29 18:08:26
agent-j
<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> 

Yes. See msdn article

You can bind to the SelectedItem of the ComboBox using a converter that compares its value for equality to the InputtedAddress and returns Brushes.Green or Brushes.Red correspondingly.

The tricky part is that the converter mentioned above would need to keep track of InputtedAdress somehow; this is quite cumbersome because we can't use ConverterParameter to bind, so we 'd need a somewhat involved converter.

On the other hand, the effect can be implemented more easily with an IMultiValueConverter. For example:

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

You would then need an IMultiValueConverter to convert the two incoming values to a Brush. This is really easy to make using the documentation-provided example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!