简体   繁体   中英

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?

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}" />

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM