nrofis
nrofis

Reputation: 9766

Binding UWP control to code behind property

I am developing UWP app and I created new user control and I want to bind it to dependency property in the control's code behind (without the datacontext).

Code Behind:

public Brush Fill
{
    get { return (Brush)GetValue(FillProperty); }
    set { SetValue(FillProperty, value); }
}

// Using a DependencyProperty as the backing store for Fill.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty FillProperty =
    DependencyProperty.Register("Fill", typeof(Brush), typeof(MyControl), new PropertyMetadata(new SolidColorBrush(Colors.Black)));

XAML:

...
<Grid>
    <Path Fill="{Binding ????}" Stretch="Fill">
        ...
    </Path>
</Grid>

I want that my path's fill property will bind to the property Fill from code behind (the data context should hold different data so I can't use it here)

How can I do that in UWP?

Upvotes: 0

Views: 2184

Answers (2)

Justin XL
Justin XL

Reputation: 39006

x:Bind would work perfectly on this. Note x:Bind will be looking for properties, methods & events defined in your XAML's code-behind. It's a more performant binding than ElementName.

<Path Fill="{x:Bind Fill, Mode=OneWay}" />

Upvotes: 3

CShark
CShark

Reputation: 1563

You should be able to use the ElementName property of a binding to circumvent the data context, just as normal WPF allows you to do.

If the property is part of the user control you'll need to assign a name via x:Name to your user control in xaml to access it

<UserControl [...] x:Name="Control"...`

Then use something like{Binding ElementName=Control, Path=Fill}, as long as Fill is a property of your user control.

Upvotes: 0

Related Questions