我想綁定視頻預覽自定義控件類中的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