如何绑定图像源

本文关键字:图像 绑定 何绑定 | 更新日期: 2023-09-27 18:17:34

我试图绑定图像源,事情是:我有一个带有filesystemwatcher的文件夹—每次向文件夹中添加新的图像文件时—我将获得图像的完整路径,并希望将其绑定到图像控件的源。因此,每次将新的TIFF文件添加到文件夹时,图像将在GUI中自动更改。

这是我所做的:

XAML:

<Window x:Class="WpfApplication2.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:WpfApplication2"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="414,159,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
        <Image x:Name="img1" HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100" RenderTransformOrigin="1.604,1.161" Source="{Binding ButtonImage}" />
    </Grid>
</Window>

MainWindow.xaml.cs

private ImageSource b;
public  ImageSource ButtonImage
{
    get { return b; }
    set
    {
        b = value;
    }
}
private void button_Click(object sender, RoutedEventArgs e)
{
    ButtonImage = new BitmapImage(new Uri(@"C:'Users'x'Desktop'1.tif"));
    watch();
}
private void watch()
{
    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = @"C:'Users'x'Desktop'ti";
    watcher.Created += new FileSystemEventHandler(OnChanged);
    watcher.EnableRaisingEvents = true;
    watcher.Filter = "*.tif";
}
private void OnChanged(object source, FileSystemEventArgs e)
{
    ButtonImage = new BitmapImage(new Uri(e.FullPath));
}

如何绑定图像源

在属性设置器中引发属性更改事件

public  ImageSource ButtonImage
{
    get { return b; }
    set
    {
        b = value;
        PropertyChanged("ButtonImage");
    }
}

创建一个视图模型并将属性移动到那里,并将视图的DataContext设置为这个视图模型

如果你正在使用后面的代码,那么不要使用绑定给图像起一个名字img.Source =价值;