【问题标题】:When binding an image source to a BitmapSource, the image stays blank将图像源绑定到 BitmapSource 时,图像保持空白
【发布时间】:2012-03-07 17:26:03
【问题描述】:

我正在尝试在 WPF 应用程序中显示来自 Kinect 的相机源。但是,图像显示为空白。

下面是我在 Kinect 课程中的一个 sn-p,这一切都正确触发,并且 BitmapSource 似乎创建得很好。

public delegate void FrameChangedDelegate(BitmapSource frame);
public event FrameChangedDelegate FrameChanged;


//this event is fired by the kinect service, and fires correctly

void sensor_AllFramesReady(object sender, AllFramesReadyEventArgs e)
    {
        using (ColorImageFrame colorFrame = e.OpenColorImageFrame())
        {
            if (colorFrame == null)
            {
                return;
            }

            byte[] pixels = new byte[colorFrame.PixelDataLength];

            colorFrame.CopyPixelDataTo(pixels);

            int stride = colorFrame.Width * 4;

            BitmapSource newBitmap = BitmapSource.Create(colorFrame.Width, colorFrame.Height,
                96, 96, PixelFormats.Bgr32, null, pixels, stride);
            counter++;

            //below is the call to the delegate

            if ( FrameChanged != null)
            {
                FrameChanged(newBitmap);
            }


        }
    }

这是我的 ViewModel 中的内容。

    void kinectService_FrameChanged(BitmapSource frame)
    {

        image = frame;
    }

    BitmapSource image;
    public BitmapSource Image
    {
        get { return this.image; }
        set
        {
            this.image = value;
            this.OnPropertyChanged("Image");
        }
    }

下面是我的 XAML 视图中的内容。

<Image Canvas.Left="212" Canvas.Top="58" Height="150" Name="image1" Stretch="Fill"     Width="200" Source="{Binding Path=Image}"/>

所有事件和属性似乎都已更新。我做错了什么?

【问题讨论】:

  • 在 FrameChanged 中尝试:this.Image = frame

标签: c# wpf bitmapsource


【解决方案1】:
image = frame;

应该是:

Image = frame;

否则您的属性更改通知将不会触发。

【讨论】:

    【解决方案2】:

    尝试改变:

     void kinectService_FrameChanged(BitmapSource frame)
     {
        this.image = frame;
     }
    

     void kinectService_FrameChanged(BitmapSource frame)
     {
        this.Image = frame;
     }
    

    因为您没有使用您的属性,所以永远不会调用 PropertyChanged 事件,因此 UI 不会知道它需要获取新的图像值。

    【讨论】:

      【解决方案3】:

      我不确定,但您不需要使用大写 I:

      void kinectService_FrameChanged(BitmapSource frame)
      {
         Image = frame;
      }
      

      忘了补充:这就是 WPF 卡住的原因。所有这些小陷阱和陷阱。我在应用程序中很少遇到绑定应该防止的“同步”问题,而现在我遇到了绑定本身的很多小问题。

      【讨论】:

      • 完全同意,主代码一切正常,但您遇到了一个您没有注意到的小问题。主要是因为您认为这必须是一个复杂的问题。
      猜你喜欢
      • 2010-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-29
      • 1970-01-01
      • 1970-01-01
      • 2020-10-06
      • 2020-07-25
      相关资源
      最近更新 更多