简体   繁体   中英

How to bind a Grid to a UserControl Property in XAML?

I have a UserControl (let's call it "CustomControl") that acts as a simple toolbar for a grid. It contains only a button to open/close (it just changes it's visibility property) a Grid.

Like this:

<UserControl ....>
...
<Grid>
    <Button x:Name="btChangeState" Content="Change State" />
</Grid>
....
</UserControl>

And I have declared the DependencyProperty of a Grid like the following:

public Grid MyContent
{
    get { return (Grid)GetValue(MyContentProperty); }
    set { SetValue(MyContentProperty, value); }
}

public static readonly DependencyProperty MyContentProperty =
    DependencyProperty.Register("MyContent", typeof(Grid), typeof(MyControl), new PropertyMetadata(null));

And my user control button has a simple handler to change the "MyContent" Grid Visible or collapsed:

if (MyContent.Visibility == Windows.UI.Xaml.Visibility.Visible)
    MyContent.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
else
    MyContent.Visibility = Windows.UI.Xaml.Visibility.Visible;

On my ViewPage, I am able to wire up the theUserControl.MyContent to theGrid in the constructor of the Page, but how can I do that in the XAML? I would like to do something like this:

<Page .....>
    <StackPanel Orientation="Vertical">
        <cs:CustomControl x:Name="theUserControl" MyContent="{Binding theGrid}" />
        <Grid x:Name="theGrid" Height="200" Width="200" Background="Red" />
    </StackPanel>
</Page>

Is it possible?

您需要使用ElementName

<cs:CustomControl x:Name="theUserControl" MyContent="{Binding ElementName=theGrid}" />

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