C# 如何使用C正确地将图像源链接绑定到wpf xaml#
在ViewModel中定义公共属性C# 如何使用C正确地将图像源链接绑定到wpf xaml#,c#,wpf,xaml,C#,Wpf,Xaml,在ViewModel中定义公共属性 Source="{Binding Path, Converter={StaticResource MyPathConverter}}" private void MyPathConverter() { try { string Path = @"http://qa-ads.transim.com/www/delivery/avw.php?zoneid=9&cb=131441234131313&n=
Source="{Binding Path, Converter={StaticResource MyPathConverter}}"
private void MyPathConverter()
{
try
{
string Path = @"http://qa-ads.transim.com/www/delivery/avw.php?zoneid=9&cb=131441234131313&n=a25d26ed";
Image image = new Image();
image.UriSource = new Uri(Path);
}
catch (Exception ex) { /*Ignoe Function*/ }
}
请看这里
Xaml:
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));
}
}
}
<Image Source="{Binding Path=ImageSource}"/>
注意:别忘了为viewModel设置DataContext
ImageSource = "http://qa-ads.transim.com/www/images/c94efa71e756c4920ac93560f9ce8520.jpg";
可能重复的?您能告诉我如何使用链接在xaml和C#中绑定图像的正确方法吗?请注意,设置
UpdateSourceTrigger=PropertyChanged
在单向绑定中无效。我已经删除了它。只是写UpdateSourceTrigger的坏习惯谢谢你的编辑:)先生这是干什么的-->这个。DataContext=new yourViewModel()?DataContext是视图查找数据的地方。请参阅此处以增加一点精度,UI元素的DataContext属性提供未明确指定源的任何绑定的源对象(通过设置source、RelativeSource或ElementName)。因此,当您编写{Binding Path=ImageSource}
时,框架希望有一个对象具有分配给当前DataContext的ImageSource属性。此外,DataContext属性值被继承到可视化树中的子元素。因此,当您设置主窗口的DataContext时,该值将自动对Image元素可用。
ImageSource = "http://qa-ads.transim.com/www/images/c94efa71e756c4920ac93560f9ce8520.jpg";
this.DataContext = new YourViewModel()