c# - WPF 图像控件源绑定(bind)

标签 c# wpf image binding properties

我是 WPF 和 C# 的新手,我尝试实现以下功能,但经过多次尝试后都失败了。谁能帮帮我?

我有一个图像控件:

<Image Grid.Row="1" x:Name="ImageEditor"  Stretch="Fill" StretchDirection="Both"/>

我想将此图像控件的源绑定(bind)到另一个类 (ImageHandler) 的静态属性

class ImageHandler
{
    public static BitmapImage ImageToDisplay { get; set; }

    public ImageHandler(){}

    .... //other codes
}

因此,每当我在 ImageHandler 类中执行某些操作并更新 ImageToDisplay 属性时,我的图像控件就会显示新图像。

我尝试了几种方法,但都没有达到这个目的。以下显示了我失败的尝试之一。

<Window.Resources>
    <local:ImageHandler x:Key="ImageHandler"></local:ImageHandler>
</Window.Resources>

<Image Grid.Row="1" x:Name="ImageEditor" Stretch="Fill" StretchDirection="Both" 
    Source="{Binding Source={StaticResource ResourceKey=ImageHandler},
    Path=ImageToDisplay,Mode=TwoWay}">
</Image>

最佳答案

您必须在 ImageHandler 中实现 INotifyPropertyChanged

对于依赖属性:

class ImageHandler : INotifyPropertyChanged
{
    private BitmapImage imageToDisplay;
    public BitmapImage ImageToDisplay
    {
        get { return imageToDisplay; }
        set
        {
            if (imageToDisplay != value)
            {
                imageToDisplay = value;
                OnPropertyChanged("ImageToDisplay");
            }
        }
    }

    public ImageHandler() { }

    // .... Other codes

    #region INotifyPropertyChanged implementation
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion
}

但是,要实现它,我必须删除 static 属性。

关于c# - WPF 图像控件源绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14551149/

相关文章:

c# - 如何在 WPF 中进行 CPU 使用控制

image - 用 Java 访问网络摄像头的最佳方式

c# - Xamarin、MySQL 异常 : unable to connect to any specific host

c# - 在 asp.net 中使用 ajax 访问 C# 方法?

c# - 禁用事件处理的设计模式

python - 如何使用python从图像中提取文本或数字

php - 需要使用 array_key_exists 从 mysql 获取数据值

C#:通过反射获取值(value)

c# - 从 c# 中的线程调用 c++ 函数时出现 system.access.violation 异常

WPF GroupBox 标题对齐问题