我想从我的资源中绑定图像而不在代码中使用其路径... 当我使用
时,这行setGreen \ Red可以正常工作完整路径
@"C:\Users\hed-b\source\repos\WpfApp4Test\WpfApp4Test\Resources\smile_green.png";
@"C:\Users\hed-b\source\repos\WpfApp4Test\WpfApp4Test\Resources\smile_red.png";
但不适用于
"Resources/smile_green.png", "Resources/smile_red.png"
或使用Resources.smile_red, Resources.smile_green
我不知道还能做些什么...
“我的图片”位于“我的项目名称/资源/我的图像”中
感谢帮助!
这是我的ViewModel
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using WpfApp4Test.Properties;
namespace WpfApp4Test
{
public class MainWindowVM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string DisplayedImagePath { get; set; }
private ICommand _SetGreen;
public ICommand StartGreen
{
get
{
if (_SetGreen == null)
{
_SetGreen = new RelayCommand((param) => setGreen());
}
return _SetGreen;
}
}
private ICommand _SetRed;
public ICommand StartRed
{
get
{
if (_SetRed == null)
{
_SetRed = new RelayCommand((param) => setRed());
}
return _SetRed;
}
}
private void setGreen() {
//DisplayedImagePath= @"C:\Users\hed-b\source\repos\WpfApp4Test\WpfApp4Test\Resources\smile_green.png";
DisplayedImagePath = "Resources/smile_green.png";
}
private void setRed()
{
//DisplayedImagePath = @"C:\Users\hed-b\source\repos\WpfApp4Test\WpfApp4Test\Resources\smile_red.png";
DisplayedImagePath = "Resources/smile_red.png";
}
}
}
这是我的视图
<Window x:Class="WpfApp4Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp4Test"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<UniformGrid Rows="1" Columns="3">
<Image Source="{Binding DisplayedImagePath ,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
<Button Content="Start Green" Command="{Binding StartGreen}"/>
<Button Content="Start Red" Command="{Binding StartRed}" />
</UniformGrid>
</Grid>
</Window>
答案 0 :(得分:2)
将图像设置为资源,即设置图像属性=>构建操作=资源并复制到输出目录=否
将图像绑定资源路径设置为Resource File Pack URI,即pack://application:,,,/AssemblyName;component/Resources/smile_green.png
,其中/AssemblyName;component
仅在从不同的引用程序集中加载图像资源时才需要。 >
您可以使用绑定转换器,它将您的字符串转换为ImageSource,即尝试以下代码
public sealed class ImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { try { return new BitmapImage(new Uri((string)value)); } catch { return new BitmapImage(); } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }