如何绑定图像源

时间:2016-11-10 22:00:50

标签: c# wpf image binding imagesource

我正在尝试绑定图像源,事情就是: 我有一个带有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));
}

1 个答案:

答案 0 :(得分:-1)

在属性设置器中提升属性已更改事件

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

创建一个viewmodel并在那里移动属性并将视图的DataContext设置为此viewmodel

如果您使用的是代码,请不要使用绑定 为图像命名 img.Source =值;