问题
I am trying to show an image stored in local directory inside XAML design.
I have the path to local image.
ImagePage.xaml
<ScrollViewer>
<ListView x:Name="ViewImage" SelectionMode="None" IsActiveView="True">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<WrapGrid Orientation="Horizontal" MaximumRowsOrColumns="1" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<Grid x:Name="imgGrid">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackPanel>
<Grid Height="50" Width="50">
<Grid Margin="2" Background="red">
<Image Source="{Binding imgArt}" Stretch="UniformToFill"
Height="40" Width="40"/>
</Grid>
</Grid>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ScrollViewer>
ImagePage.xaml.cs
string strImgPath = "ms-appx:///Images/Music/localImg.png";
public string imgPath
{
get { return strImgPath; }
}
imageClaz obj = new imageClaz();
obj.imgArt = imgPath;
imageClaz()
public class imageClaz
{
public string imgArt { get; set; }
}
回答1:
You should use Windows.UI.Xaml.Media.Imaging.BitmapImage if you are targeting WinRT app.
Just change the imgArt froms string to BitmapImage
public class imageClaz
{
public BitmapImage imgArt { get; set; }
}
and set the Image like this,
string strImgPath = "ms-appx:///Images/Music/localImg.png";
imageClaz obj = new imageClaz();
obj.imgArt = new BitmapImage(new Uri(strImgPath, UriKind.Absolute));
回答2:
Both answers about BitmapImage are only partially right. In fact XAML has a build in converter and you can surely pass there a string unless you provide a converter. There may be several problems in your code:
you are not notifying UI about the change of the property - lack of INotifyPropertyChanged:
Example :
public sealed partial class MainPage : Page, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); } } private string imgArt; public string ImgArt { get { return imgArt; } set { imgArt = value; OnPropertyChanged("ImgArt"); } }
the second thing - I'm not sure if you had set the DataContext of image or its parents:
public MainPage() { this.InitializeComponent(); DataContext = this; }
A sample you can download from GitHub.
回答3:
Source is of type ImageSource, not string. You can set the view model with something like this:
public class ImageClaz
{
public ImageClaz(Uri uri)
{
this.ImgArt = new BitmapImage(uri);
}
public ImageSource ImgArt { get; set; }
}
Where you use the path to create the Uri:
var imgeClass = new ImageClaz(new Uri("ms-appx:///Images/Music/localImg.png"));
来源:https://stackoverflow.com/questions/27163604/cannot-implicitly-convert-type-string-to-windows-ui-xaml-media-imaging-bitmap