Datacontext conflicts

后端 未结 1 892
名媛妹妹
名媛妹妹 2020-11-29 13:54


        
相关标签:
1条回答
  • 2020-11-29 14:43

    In a UserControl like this you should never exlicitly set the DataContext to this or anyting else, because the DataContext is usually set externally when you use the UserControl somewhere in your application. The externally applied DataContext is typically (part of) the application's view model.

    You should instead change your internal bindings so that they use an explicit RelativeSource:

    <TextBlock
        Text="{Binding Path=Watermark,
                       RelativeSource={RelativeSource AncestorType=UserControl},
                       FallbackValue=This prompt dissappears as you type...}"
        Visibility="{Binding ElementName=txtUserEntry,
                             Path=Text.IsEmpty,
                             Converter={StaticResource BooleanToVisibilityConverter}}" />
    <TextBox
        Name="txtUserEntry"
        Text="{Binding Path=Text,
                       UpdateSourceTrigger=PropertyChanged,
                       RelativeSource={RelativeSource AncestorType=UserControl}}" />
    

    and then remove any DataContext assignment from the UserControl's constructor.

    See e.g. this answer (and many other similar) that discuss this topic in detail.

    0 讨论(0)
提交回复
热议问题