【问题标题】:How to bind a Grid to a UserControl Property in XAML?如何将 Grid 绑定到 XAML 中的 UserControl 属性?
【发布时间】:2015-08-25 16:00:03
【问题描述】:

我有一个 UserControl(我们称之为“CustomControl”),它充当网格的简单工具栏。它只包含一个按钮来打开/关闭(它只是改变它的可见性属性)一个网格。

像这样:

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

我已经声明了 Grid 的 DependencyProperty,如下所示:

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));

我的用户控制按钮有一个简单的处理程序来更改“MyContent”网格可见或折叠:

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

在我的 ViewPage 上,我可以在 Page 的构造函数中将 theUserControl.MyContent 连接到 theGrid,但是如何在 XAML 中做到这一点?我想做这样的事情:

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

有可能吗?

【问题讨论】:

    标签: c# xaml user-controls windows-phone-8.1 windows-phone


    【解决方案1】:

    你需要使用ElementName:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-18
      • 2011-07-22
      相关资源
      最近更新 更多