Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}
like image 609
Jiew Meng Avatar asked Nov 17 '10 06:11

Jiew Meng


2 Answers

Try using the following binding:

<MarkdownEditor DataContext="{Binding RelativeSource={RelativeSource Self}}" />
like image 167
Alex B Avatar answered Nov 07 '22 10:11

Alex B


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>
like image 22
Steven Jeuris Avatar answered Nov 07 '22 10:11

Steven Jeuris