WPF 图像控件源绑定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14551149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 07:14:55  来源:igfitidea点击:

WPF Image Control Source Binding

c#wpfimagebindingproperties

提问by ZhouningMan

I am new to WPF and C#, I try to implement the following feature, but failed after a lot of attempts. Can anyone help me out?

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

I have an image control:

我有一个图像控件:

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

I want to bind the source of this image control to a static property of another class (ImageHandler)

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

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

    public ImageHandler(){}

    .... //other codes
}

So whenever I do something in the ImageHandlerclass, and update the ImageToDisplayproperty, my image control will display the new image.

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

I have try several methods, but none of them achieved this goal. The following shows one of my failed attempts.

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

<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>

采纳答案by Cédric Bignon

You have to implement either INotifyPropertyChangedin ImageHandler

你必须INotifyPropertyChangedImageHandler

For dependency property :

对于依赖属性:

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
}

However, to implement it, I had to remove the staticattribute.

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