I have a ComboBox
as below. What I want is to bind the SelectedItem
value to a Text
property of a DataContext
so that another DataTemplate
can show the Image
. Please note that the ComboBox
and target Image
elements are on two different DataTemplate
s so that's why I need to update the Text
property (ImageName) of DataContext
in the backend.开发者_Go百科
<ComboBox x:Name="cboOverlay" Grid.Row="0" Grid.Column="1" SelectedIndex="0" >
<ComboBoxItem Name="BC_OL" IsSelected="True">
<StackPanel Orientation="Horizontal">
<Image Source="Images\BC_OL.jpg" Width="100" Height="25" Canvas.Top="0" Canvas.Left="0" />
<TextBlock Width="100" VerticalAlignment="Center" TextAlignment="Center"><Bold>Image1</Bold></TextBlock>
</StackPanel>
</ComboBoxItem>
<ComboBoxItem Name="Indian_OL">
<StackPanel Orientation="Horizontal">
<Image Source="Images\Indian_OL.jpg" Width="100" Height="25" Canvas.Top="0" Canvas.Left="0" />
<TextBlock Width="100" VerticalAlignment="Center" TextAlignment="Center"><Bold>Image2</Bold></TextBlock>
</StackPanel>
</ComboBoxItem>
</ComboBox>
<Image Source="{Binding Path=Image}" Width="81" Height="25" Canvas.Top="0" Canvas.Left="0" />
You can set each item to have a specific data context.
I'm not sure in your xaml which item you are trying to set, I think it's the last line the
<Image Source="{Binding Path=Image' ... />
You can just specify the data context for that control.
Edit In reponse to comments
Since you are trying to get the selected item from the combo box and trying to send that over to the image, why not just pass it in as a value into the class that is holding the image.
I think you could do this in xaml but I'm not entirely sure how to do it.
It seems like you're trying to do something like this:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<DockPanel>
<TextBox DockPanel.Dock="Top" x:Name="Source">x1</TextBox>
<ComboBox DockPanel.Dock="Top" x:Name="myComboBox"
SelectedValue="{Binding ElementName=Source, Path=Text, Mode=TwoWay}">
<sys:String>1</sys:String>
<sys:String>22</sys:String>
<sys:String>333</sys:String>
<sys:String>4444</sys:String>
</ComboBox>
<TextBlock DockPanel.Dock="Top"
Text="{Binding ElementName=myComboBox, Mode=OneWay, Path=SelectedItem.Length}"/>
</DockPanel>
</Page>
The ComboBox
is bound to the text of the TextBox
using two-way binding, so when you select an item from the ComboBox
it updates the TextBox
, and when you type a value into the TextBox
that's in the ComboBox
's list it changes the selected item in the ComboBox
.
The TextBlock
is bound to a property of the selected item in the ComboBox
. Whenever the selected item changes, whether because the user selected a new one or the value in the TextBox
changed, the TextBlock
gets updated.
But I'm confused by all your talk about data contexts. None of the objects in the example you posted have data contexts.
精彩评论