Jiew Meng
Jiew Meng

Reputation: 88207

How to set binding source to "self"/UserControl Code Behind

How can I set a Binding Source to point to "this" UserControl CodeBehind? Eg. From a UserControl MarkdownEditor.xaml, I want to point to properties within MarkdownEditor.xaml.cs. Doing this without setting DataContext = this

Update: My Solution

This is what I did tho I marked @Alex B's solution as answer. I didn't want to set the DataContext of the entire control to Self, as I am binding to other objects too

{Binding RelativeSource={RelativeSource AncestorType={x:Type local:MarkdownEditor}}, Path=Options.FontFamily}

Upvotes: 9

Views: 16166

Answers (2)

Steven Jeuris
Steven Jeuris

Reputation: 19100

Instead of using your proposed extensive expression:

{Binding RelativeSource={RelativeSource AncestorType={x:Type local:MarkdownEditor}}, Path=Options.FontFamily}

Isn't it easier just setting x:Name of the UserControl?

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

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

</UserControl>

Upvotes: 7

Alex B
Alex B

Reputation: 2814

Try using the following binding:

<MarkdownEditor DataContext="{Binding RelativeSource={RelativeSource Self}}" />

Upvotes: 8

Related Questions