在WPF中没有调用属性绑定更改的Setter函数

时间:2015-10-19 12:54:53

标签: wpf vb.net

我在用户控件中有一小段代码。那段代码注册了一个属性,如下所示

    Public Shared ValueProperty As DependencyProperty = DependencyProperty.Register("Value", GetType(String), GetType(AutoCompleteBox))
Public Property Value() As String
    Get
        Return Me.GetValue(ValueProperty).ToString
    End Get
    Set(value As String)
        Me.SetValue(ValueProperty, value)
    End Set
End Property

简单的东西,对。到目前为止没什么特别的。在同一个控件中,我有一个带有以下绑定的文本框

Text="{Binding RelativeSource={RelativeSource Self}, Path=Value, Mode=TwoWay}"

它应该是非常简单的东西。遗憾的是,此代码导致null异常,因为Setter方法根本没有被调用。我想,我可能记错了,或者遗漏了什么。但是,我已经通过五个不同的教程来创建这个属性,但它是同样的问题。

编辑:

控件的完整XAML。我想根据searchtext属性更改更新此控件中的value属性。我尝试用普通的文本框替换自动完成,同样的问题。

<UserControl x:Class="AutoCompleteBox"
         xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation" 
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" xmlns:UC="clr-namespace:SMS" >
<StackPanel Margin="0">
    <StackPanel Orientation="Horizontal" FlowDirection="LeftToRight">
        <Label Content="" Width="auto" x:Name="AutocompleteLabel" Style="{DynamicResource LabelStyle}" Visibility="Collapsed"/>
        <Label Content="*" Width="auto" x:Name="MandatoryLabel" Style="{DynamicResource LabelStyle}" FontSize="22" Foreground="Red" Visibility="Collapsed"/>
    </StackPanel>
    <telerik:RadAutoCompleteBox x:Name="AutoCompleteTextBox" SearchText="{Binding RelativeSource={RelativeSource Self}, Path=Value, Mode=TwoWay}" KeyboardNavigation.TabNavigation="Local" TextSearchMode="Contains" AutoCompleteMode="Suggest" Height="30" Margin="0,0,5,0" GotFocus="AutoCompleteTextBox_GotFocus" KeyUp="AutoCompleteTextBox_KeyUp" telerik:StyleManager.Theme="Windows8" SelectionMode="Single"></telerik:RadAutoCompleteBox>
</StackPanel>

编辑:

问题的屏幕截图。 http://imgur.com/a/w97bY

1 个答案:

答案 0 :(得分:1)

您创建的DependencyProperty默认值为Nothing(C#中为null)。所以当你调用GetValue(ValueProperty).ToString时,当然会抛出NullReferenceException。您应该做的是使用TryCast以安全的方式将其投放到String

Return TryCast(Me.GetValue(ValueProperty), String)

编辑 :代码中的Binding肯定会失败,Value属性在AutoCompleteBox中定义,因此绑定应查找AutoCompleteBoxUserControl)的可视树,如下所示:

SearchText="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, 
             Path=Value, Mode=TwoWay}"