我正在构建一个Videoplayer自定义控件(名为WpfCustomControlLibrary1的项目),并希望添加一个加载命令。
这是我在课堂上添加以获取此命令的内容:
Public Class VideoPlayer
Inherits Control
...
Public Shared ReadOnly LoadCommad As RoutedUICommand
....
Shared Sub New()
'This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class.
'This style is defined in Themes\Generic.xaml
DefaultStyleKeyProperty.OverrideMetadata(GetType(VideoPlayer), New FrameworkPropertyMetadata(GetType(VideoPlayer)))
LoadCommad = New RoutedUICommand("Load", "Load Video", GetType(VideoPlayer))
CommandManager.RegisterClassCommandBinding(GetType(VideoPlayer), New CommandBinding(LoadCommad, AddressOf OnLoadExecuted))
End Sub
...
这就是我从我的XAML中调用它的方式:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfCustomControlLibrary1">
.....
<Button Command="local:VideoPlayer.LoadCommand"
DockPanel.Dock="Right" Margin="0 5 5 0"
Width="30" HorizontalAlignment="Left"
Content="..." />
.....
但是当我将这个Usercontrol添加到这样的新项目时:
<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:bibli="clr-namespace:EigeneControllsBibli;assembly=EigeneControllsBibli"
xmlns:uc="clr-namespace:WpfCustomControlLibrary1;assembly=WpfCustomControlLibrary1"
Title="Window1" Height="442" Width="804">
<Grid>
<uc:VideoPlayer Source="C:\Users\Public\Videos\Sample Videos\Bear.wmv" Margin="0,106,369,0"></uc:VideoPlayer>
</Grid>
我得到一个错误,他无法将属性“命令”中的字符串转换为类型为“System.Windows.Input.ICommand
的对象有人看到有什么问题吗?
感谢您的帮助, 尼科
答案 0 :(得分:1)
LoadCommad = New RoutedUICommand("Load", "Load Video", GetType(VideoPlayer))
应该是
LoadCommand = New RoutedUICommand("Load", "Load Video", GetType(VideoPlayer))
我不知道这是否会产生错误,但也许。
答案 1 :(得分:0)
我认为您要做的是将LoadCommand声明为实例而不是共享变量,因此:
Public Class VideoPlayer
Inherits Control
...
Private ReadOnly m_LoadCommand As RoutedUICommand
....
Shared Sub New()
'This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class.
'This style is defined in Themes\Generic.xaml
DefaultStyleKeyProperty.OverrideMetadata(GetType(VideoPlayer), New FrameworkPropertyMetadata(GetType(VideoPlayer)))
End Sub
Sub New()
m_LoadCommand = New RoutedUICommand("Load", "Load Video", GetType(VideoPlayer))
End Sub
Public Property LoadCommand As ICommand
Get
Return m_LoadCommand
End Get
End Property
...
然后绑定XAML中的Button.Command属性,所以:
<StackPanel>
<uc:VideoPlayer x:Name="myPlayer" Source="C:\Users\Public\Videos\Sample Videos\Bear.wmv" Margin="0,106,369,0"></uc:VideoPlayer>
<Button Command="{Binding ElementName=myPlayer, Path=LoadCommand"
Width="30"
Content="..." />
</StackPanel>