如何将绑定源设置为"self"/ UserControl Code Behind

Jie*_*eng 7 data-binding wpf

如何设置绑定源指向"此"UserControl CodeBehind?例如.从UserControl MarkdownEditor.xaml,我想指向其中的属性MarkdownEditor.xaml.cs.没有设置就这样做DataContext = this

更新:我的解决方案

这就是我所做的,我将@Alex B的解决方案标记为答案.我不想DataContext将整个控件设置为Self,因为我也绑定到其他对象

{Binding RelativeSource={RelativeSource AncestorType={x:Type local:MarkdownEditor}}, Path=Options.FontFamily}
Run Code Online (Sandbox Code Playgroud)

Ale*_*x B 9

尝试使用以下绑定:

<MarkdownEditor DataContext="{Binding RelativeSource={RelativeSource Self}}" />
Run Code Online (Sandbox Code Playgroud)


Ste*_*ris 6

而不是使用您提出的广泛表达:

{Binding RelativeSource={RelativeSource AncestorType={x:Type local:MarkdownEditor}}, Path=Options.FontFamily}
Run Code Online (Sandbox Code Playgroud)

是不是很容易只设置x:NameUserControl

<UserControl
        ...
    x:Name="Control">

    <TextBlock Text="{Binding ElementName=Control, Path=SomeText}" />

</UserControl>
Run Code Online (Sandbox Code Playgroud)