views:

38

answers:

1

I have a custom UserControl called (for instance) MyPanel, and I want to use it in another XAML file. I would like to set a property of MyPanel, such as "Title" in the XAML file into which MyPanel is placed, as follows:

<UserControl x:Name="ContainerControl">
    <local:MyPanel Title="Whatever I Want" />
</UserControl>

I would like for the "Title" property of MyPanel to then populate a TextBlock in MyPanel. How do I set up the code and/or XAML in MyPanel to support such a property?

I'm not even sure this is considered binding, so excuse my ignorance if this is wrong.

+2  A: 

The simplest solution I can think of is:-

MyPanel xaml :-

<UserControl x:Class="SilverlightApplication1.MyPanel" ...>
  <Grid x:Name="LayoutRoot">
    <TextBlock x:Name="txtTitle" />
    <!-- other stuff here -->
  </Grid>
</UserControl>

MyPanel.cs :-

public partial class MyPanel : UserControl
{
  // constructor stuff here.

  public string Title
  {
      get { return txtTitle.Text; }
      set { txtTitle.Text = value; }
  } 
}

There are other "clever" solutions but this is good enough for this requirement.

AnthonyWJones
Perfect! And obvious in retrospect. I was worried I needed to make it a full-blown DependencyProperty or whatever.
Klay
In this case a DependencyProperty isn't needed, I prefer to give the simplest solution necessary. However if you ever wanted to re-use the `MyPanel` control and data bind the `Title` property you would need to implement it as a DependencyProperty.
AnthonyWJones