WPF技术问询:如何将First_Image的Source绑定到Second_Image的Tag
Hey there! Let's fix up your XAML so First_Image pulls its Source directly from Second_Image's Tag property. Here are two simple, reliable ways to do this:
1. XAML Binding (Recommended)
This is the most "WPF-native" approach, using declarative binding to link the two properties directly in your markup. Replace your existing First_Image definition with this:
<Image Name="First_Image" Source="{Binding ElementName=Second_Image, Path=Tag}" Canvas.ZIndex="2" Width="80" Height="80" Canvas.Top="0" Canvas.Left="10"/>
How it works:
ElementName=Second_Imagetells WPF to target the image with that name as the binding source.Path=Tagspecifies we want to use theTagproperty value from that element.- WPF automatically converts the string value in
Tagto anImageSource(the type required forImage.Source), so you don't need extra conversion code.
Your full updated XAML will look like this:
<Canvas Width="100" Height="120"> <Image Name="First_Image" Source="{Binding ElementName=Second_Image, Path=Tag}" Canvas.ZIndex="2" Width="80" Height="80" Canvas.Top="0" Canvas.Left="10"/> <Image Name="Second_Image" Uid="{Binding XPath=@Name}" Canvas.ZIndex="2" Width="80" Height="20" Canvas.Bottom="20" Canvas.Left="10" MouseLeftButtonDown="TTX" Tag="/Images/Image.png" Style="{StaticResource Function}"/> </Canvas>
2. Code-Behind Approach
If you prefer or need to set this in C# code (for example, if you're dynamically creating elements), you can do this in your window/user control's Loaded event, or Second_Image's Loaded event:
private void Window_Loaded(object sender, RoutedEventArgs e) { if (Second_Image.Tag is string imagePath) { First_Image.Source = new BitmapImage(new Uri(imagePath, UriKind.RelativeOrAbsolute)); } }
Just make sure to hook up the Loaded event in your XAML (e.g., add Loaded="Window_Loaded" to your root window/UserControl element).
Quick Note:
Double-check that the path in Second_Image.Tag is valid. If it's a relative path, ensure your image file has its Build Action set to Resource or Content in the project properties—this ensures WPF can locate the image correctly.
内容的提问来源于stack exchange,提问作者Mohammad Farahi

