Silverlight - 用户控件绑定

时间:2009-12-03 13:26:09

标签: silverlight user-controls

我正在学习Silverlight。在这个过程中,我正在尝试构建一个自定义用户控件。我的最终目标是能够在XAML中编写以下语句:

<my:CustomControl>
  <my:CustomControl.MainControl>
    <Canvas><TextBlock Text="Hello!" /></Canvas>
  </my:CustomControl.MainContent>
</my:CustomControl>

控件的内容将包装在自定义边框中。再一次,这只是一次学习练习。要附加我的边框,我创建了以下UserControl:

<UserControl x:Class="CustomControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">

    <Grid x:Name="LayoutRoot">
      <Border>
        <!-- CustomControl Content -->
      </Border>
    </Grid>
</UserControl>

此文件的代码隐藏如下所示:

public partial class CustomControl : UserControl
{
  public UIElement MainContent
  {
    get { return (UIElement)GetValue(MainContentProperty); }
    set { SetValue(MainContentProperty, value); }
  }

  public static readonly DependencyProperty MainContentProperty =
    DependencyProperty.Register("MainContent", typeof(UIElement), typeof(CustomControl),  
    new PropertyMetadata(null));


  public CustomControl()
  {
    InitializeComponent();            
  }
}

我遇到的问题是让MainContent出现在我的CustomControl中。我确信我正确设置它,但我不确定如何显示它。我真的希望它成为DependencyProperty,所​​以我可以利用数据绑定和动画。

如何让MainContent出现在CustomControl中?谢谢

1 个答案:

答案 0 :(得分:2)

首先,你需要等到解析其余的控件,这样你才需要挂钩加载的事件: -

public CustomControl()
{
    InitializeComponent();
    Loaded += new RoutedEventHandler(CustomControl_Loaded);
}

然后在加载的事件中将MainControl属性分配给边框的Child属性。如果你给你的边界一个x:Name这是最好的,现在我简单地称之为“边界”。

void CustomControl_Loaded(object sender, RoutedEventArgs e)
{
    border.Child = MainControl;
}

那会让你前进。当然,您可能需要处理动态更改的MainControl属性,因此您需要在控件中添加bool isLoaded字段并在加载的事件中设置该字段。如果为true,则MainControl设置者应将传入值分配给border.Child

事情可能开始变得更加复杂,事实上我不推荐这种方法来创建自定义控件。有关更好的方法,请参阅Creating a New Control by Creating a ControlTemplate