我有一个简单的Button用户控件,用于汇总代码中的所有按钮功能:
Partial Public Class CommandButton
Inherits UserControl
Implements INotifyPropertyChanged
Public ReadOnly ButtonCmdProperty As DependencyProperty = DependencyProperty.Register("ButtonCmd", GetType(ICommand), GetType(CommandButton), New PropertyMetadata(Nothing, New PropertyChangedCallback(AddressOf OnButtonCmdChanged)))
Public ReadOnly ButtonTextProperty As DependencyProperty = DependencyProperty.Register("ButtonText", GetType(String), GetType(CommandButton), New PropertyMetadata("Undefined", New PropertyChangedCallback(AddressOf OnButtonTextChanged)))
Public Sub New()
InitializeComponent()
End Sub
#Region "ButtonCmd"
Public Property ButtonCmd As ICommand
Get
Return DirectCast(GetValue(ButtonCmdProperty), ICommand)
End Get
Set(value As ICommand)
SetValue(ButtonCmdProperty, value)
End Set
End Property
Private Sub OnButtonCmdChanged()
OnPropertyChanged("ButtonCmd")
End Sub
#End Region
#Region "ButtonText"
Public Property ButtonText() As String
Get
Return DirectCast(GetValue(ButtonTextProperty), String)
End Get
Set(value As String)
SetValue(ButtonTextProperty, value)
End Set
End Property
Private Sub OnButtonTextChanged(d As DependencyObject, e As DependencyPropertyChangedEventArgs)
OnPropertyChanged("ButtonText")
End Sub
#End Region
End Class
以下是我在XAML代码中使用它的示例:
<controls:CommandButton x:Name="btnEdit"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Height="Auto"
Width="100"
Grid.Column="0"
ButtonCmd="{Binding EditButton.ButtonCmd}"
ButtonText="{Binding EditButton.ButtonText, Mode=TwoWay}"
ButtonTooltip="{Binding EditButton.ButtonTooltip}"
IconHeight="{Binding EditButton.IconHeight}"
IconWidth="{Binding EditButton.IconWidth}"
IconSource="{Binding EditButton.IconSource}"
IsVisible="{Binding EditButton.IsVisible}"
ShowIcon="{Binding EditButton.ShowIcon}"
ShowText="{Binding EditButton.ShowText}" />
(如你所见,还有很多其他属性,但为了简洁起见,我省略了它们。) 我在VS2010中使用相同的代码超过2年没有任何问题。自升级到VS2013以来,我使用此按钮的每个页面都会抛出错误消息:
类型System.Windows.Data.BindingExpression
的对象无法转换为System.String
每个绑定。它似乎不会影响用户控件在运行时的工作方式,但在编写XAML时我无法再看到画布。 (IE.XAML不会在画布区域渲染)我很确定我已经正确编写了依赖属性,但我想我会把它扔出去看看我是否遗漏了某些内容或是否有办法禁用此错误检查。