【问题标题】:Making an easy to use UserControl via Properties通过属性制作易于使用的用户控件
【发布时间】:2012-05-29 21:41:06
【问题描述】:

在我的 Silverlight 4 应用程序中,我尝试创建一个简单的 UserControl,它将由我的应用程序使用。为了简单起见,它应该有一个“标题”和一个占位符,我想在其中放置任何类型的控件。

<User Control ...>
  <Grid x:Name="LayoutRoot">
    <TextBlock x:Name="TextBlockHeader" Text="{Binding Title}" />
    <ContentPresenter x:Name="ContentPresenterObject" />
  </Grid>
</UserControl>

在后面的代码中,我为TextBlock的文本创建了一个属性

public string Title
{
  get { return (string)GetValue(TitleProperty); }
  set { SetValue(TitleProperty, value); }
}

public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(MyAccordion), null);

这样,当我在我的应用程序中使用控件时,我可以设置 Title 属性。

<local:MyAccordion Title="Test"/>

但似乎文本块 Text="{Binding Title}" 处的绑定不会使文本“测试”显示为文本块文本。

我的问题是:如何使属性标题显示为文本框文本以及如何为 - 任何类型的用户控件可包含 - 内容控件执行此操作?

提前致谢,
弗兰克

【问题讨论】:

    标签: silverlight user-controls dependency-properties


    【解决方案1】:

    可能没有设置控件或页面的 DataContext。 - 首先,您应该阅读有关绑定的更多信息(“http://www.silverlight.net/learn/data-networking/binding/data-binding-to-controls-(silverlight-quickstart)”)。如果您正在从事实际项目并且将设计一些架构,您应该阅读有关 MVVM 模式的内容。

    【讨论】:

    • 这是了解 Silverlight 技术的第一步
    • 这解释了如何在后面的代码中绑定给定的数据。但我想将 TextBlock.Text 属性绑定到我的自定义属性 TitleProperty
    【解决方案2】:

    答案是 ElementPropertyBinding。我需要在 Binding 中引用 User Control 或者在构造函数中添加绑定。

    在 XAML 中创建绑定:

    <User Control ... x:Name="userControl">
      ...
      <TextBlock x:Name="TextBlockHeader" Text="{Binding Title, ElementName=userControl}" />
    </UserControl>
    

    在构造函数中创建绑定(代码隐藏)

    public MyUserControl()
    {
      // Required to initialize variables
      InitializeComponent();
    
      TextBlockHeader.SetBinding(TextBlock.TextProperty, new System.Windows.Data.Binding() { Source = this, Path = new PropertyPath("Title") });
    }
    

    我仍然需要了解如何添加子控件,但这是另一个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-31
      相关资源
      最近更新 更多