如何使用C#将图像源链接正确绑定到wpf xaml

时间:2017-12-15 06:54:37

标签: c# wpf xaml

<StackPanel x:Uid="Style_1" x:Name="ForAdsImagePath" Grid.Row="1" Orientation="Horizontal" Margin="0,17,0,0" Visibility="Collapsed" HorizontalAlignment="Center" VerticalAlignment="Stretch">
    <Image x:Name="img1" Source="http://xxx.xxx.xxx.com/www/deliver/xxx.php?zoneid=9&amp;cb=131441234131313&amp;n=a25d26ed" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MouseLeftButtonDown="Image_MouseLeftButtonDown"/>             
</StackPanel>

如何在C#中编写用于绑定图像源的代码。

我尝试了这一步,但初始化时出错:

Source="{Binding Path, Converter={StaticResource MyPathConverter}}"
private void MyPathConverter()
{
    try
    {
        string Path = @"http://qa-ads.transim.com/www/delivery/avw.php?zoneid=9&amp;cb=131441234131313&amp;n=a25d26ed";
        Image image = new Image();
        image.UriSource = new Uri(Path);
    }
    catch (Exception ex) { /*Ignoe Function*/ }
}

1 个答案:

答案 0 :(得分:1)

在ViewModel中定义公共属性

public class YourViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private string imageSource;

    public string ImageSource
    {
        get { return imageSource; }
        set
        {
            imageSource = value;
            RaisePropertyChanged(nameof(ImageSource));
        }
    }
}

请点击此处查看INotifyPropertyChanged

<强>的Xaml:

<Image Source="{Binding Path=ImageSource}"/>

<强>用法:

ImageSource = "http://qa-ads.transim.com/www/images/c94efa71e756c4920ac93560f9ce8520.jpg";

注意:不要忘记将DataContext设置为viewModel。

this.DataContext = new YourViewModel()