我想绑定视频预览自定义控件类中的IntPtr VidHandle属性到它的视图模型(vm:DebugHiResCameraWindowViewModel)中的IntPtr PreviewHandle。ViewModel属性没有更新时,它是相应的CustomControl属性更新
在VideoPreview的构造,我呼吁:
this.VidHandle = picBox.Handle;
更新VideoPreview的VidHandleProperty的DependencyProperty。这工作完美。但是,ViewModel中的PreviewHandle属性未被更新。到时候我打电话:
camera.StartVideoStream(PreviewHandle);
在视图模型,PreviewHandle是0,因为它从来没有从VideoPreview更新。我有感觉我的DependencyProperty VidHandleProperty没有正确实现,但我可能是错的。
下面是一些代码片段:
主窗口XAML:
<Window
x:Class="AoiImageLift.Views.DebugHiResCameraWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:AoiImageLift.Presentation.ViewModels"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
xmlns:com="clr-namespace:AoiImageLift.Components"
xmlns:local="clr-namespace:AoiImageLift"
Title="DebugHiResCameraWindow"
Name="hiResWindow"
Height="300"
Width="300">
<Window.Resources>
<vm:DebugHiResCameraWindowViewModel x:Key="viewModel"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<com:VideoPreview
DataContext="{StaticResource viewModel}"
x:Name="videoHost"
VidHandle="{Binding PreviewHandle, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type com:VideoPreview}}}"/>
<Button
DataContext="{StaticResource viewModel}"
Grid.Row="1"
Width="100"
Height="40"
Command="{Binding StartCaptureCommand}"
Content="Start"/>
</Grid>
VideoPreview类:
public class VideoPreview : WindowsFormsHost
{
private PictureBox picBox;
public static readonly DependencyProperty VidHandleProperty =
DependencyProperty.Register(
"VidHandle",
typeof(IntPtr),
typeof(VideoPreview),
new FrameworkPropertyMetadata
{
BindsTwoWayByDefault = true
});
public VideoPreview() : base()
{
picBox = new PictureBox();
picBox.Width = (int) this.Width;
picBox.Height = (int) this.Height;
this.VidHandle = picBox.Handle;
this.Child = picBox;
}
public IntPtr VidHandle
{
get
{
return (IntPtr) GetValue(VideoPreview.VidHandleProperty);
}
set
{
SetValue(VideoPreview.VidHandleProperty, value);
}
}
}
视图模型类:
public class DebugHiResCameraWindowViewModel : ViewModel
{
private Uri capturedImage;
private BitmapImage bmp;
private ISnapImages camera;
public DebugHiResCameraWindowViewModel()
{
camera = LumeneraCamera.Instance;
bmp = new BitmapImage();
}
public IntPtr PreviewHandle { get; set; }
public Uri CapturedImage
{
get { return capturedImage; }
set { capturedImage = value; OnPropertyChanged("CapturedImage"); }
}
public ICommand StartCaptureCommand
{
get
{
return new DelegateCommand(() =>
{
try
{
camera.StartVideoStream(PreviewHandle);
}
catch (CustomException ex)
{
MessageBox.Show(ex.Message, ex.Caption, ex.Button, ex.Image);
}
});
}
}
}
该控件的构造函数中的'this.VidHandle = picBox.Handle;'行在绑定前执行'VidHandle =“{Binding PreviewHandle ...''成立。因此绑定将简单地覆盖'VidHandle'的值。你也许可以在'VidHandle'改变回调的属性中设置'picBox.Handle'。 – Clemens 2014-09-24 20:51:19