如果您不想预加载图像,则必须在主窗口上创建一个依赖属性。您还必须使用WPF Pack URIs。XAML 和代码隐藏文件如下所示:
XAML:
<Window x:Class="TestWPFApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestWPFApp"
Title="MainWindow" Height="550" Width="725">
<Grid x:Name="MainGrid">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Grid.Row="0">
<Label Content="Select Image" Width="100" Height="30" Margin="10,10,100,10"></Label>
<ComboBox x:Name="cbImageSelect" Height="20" Width="400" SelectionChanged="ComboBox_SelectionChanged" />
</StackPanel>
<ContentPresenter x:Name="contentPresenter" Width="250" Height="250" Grid.Row="1" >
<ContentPresenter.Content>
<Image Source="{Binding ImageUri}" Width="220" Height="220">
</Image>
</ContentPresenter.Content>
</ContentPresenter>
</Grid>
</Window>
XAML.cs
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
namespace TestWPFApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
cbImageSelect.ItemsSource = new List<string>() { "test1.bmp", "test2.bmp" };
}
public static readonly DependencyProperty ImageUriProperty = DependencyProperty.Register("ImageUri", typeof(string), typeof(MainWindow));
public string ImageUri
{
get { return (string)GetValue(ImageUriProperty); }
set { SetValue(ImageUriProperty, value); }
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ImageUri = "pack://application:,,,/" + ((sender as ComboBox).SelectedItem as string);
}
}
}
图像位置:test1.bmp 和 test2.bmp
test1.bmp 和 test2.bmp 的属性