You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF技术问询:如何将First_Image的Source绑定到Second_Image的Tag

Bind First_Image's Source to Second_Image's Tag in WPF

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:

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_Image tells WPF to target the image with that name as the binding source.
  • Path=Tag specifies we want to use the Tag property value from that element.
  • WPF automatically converts the string value in Tag to an ImageSource (the type required for Image.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:38:35