DependencyProperty does not work if the value is from a binding

后端 未结 2 1129
一向
一向 2021-01-29 14:37

I created UserControl with viewmodel. It has DependencyProperty which only works if the value is passed directly. If the value is passed through the binding, it no longer works.

相关标签:
2条回答
  • 2021-01-29 14:52

    There is no IsConnected property in the SomeViewModel instance in the current DataContext of the UserControl, hence the Binding

    <local:SomeView Active="{Binding IsConnected}" />
    

    won't work. It tries to resolve the PropertyPath against the current DataContext, unless you explicitly specify its Source, RelativeSource or ElementName.

    This is the exact reason why UserControls should never explicitly set their own DataContext, and hence never have something like an own, private view model.

    The elements in the UserControl's XAML would not bind to properties of such a private view model object, but directly to the properties of the UserControl, for example like

    <TextBlock Text="{Binding Active,
        RelativeSource={RelativeSource AncestorType=UserControl}}"/>
    
    0 讨论(0)
  • 2021-01-29 14:53

    When you set the DataContext explicitly in the UserControl like this:

    <UserControl.DataContext>
        <viewModels:SomeViewModel />
    </UserControl.DataContext>
    

    ...you can no longer bind to SomeView's DataContext in the consuming view like this:

    <local:SomeView Active="{Binding IsConnected}" />
    

    ...because SomeViewModel doesn't have any IsConnected property.

    You should avoid setting the DataContext explicitly and let the UserControl inherit its DataContext from its parent element. You can still bind to the dependency property of the UserControl itself using a RelativeSource or an ElementName:

    <UserControl ...>
        <Grid>
            <TextBlock Text="{Binding Active, RelativeSource={RelativeSource AncestorType=UserControl}}" />
        </Grid>
    </UserControl>
    

    Besides, SomeViewModel seems superfluous in your example since the UserControl already has an Active property.

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