tags:

views:

25

answers:

2

I need to simply provide the content of a property to a custom User Control in Silverlight.

My control is something like this:

<UserControl x:Class="SilverlightApplication.Header"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignWidth="300" d:DesignHeight="120">

<Grid x:Name="Header_Layout">
    <StackPanel x:Name="hiHeaderContent" Width="Auto" Margin="73,8,8,8">
        <TextBlock x:Name="User:" Text="{Binding name}" />
</StackPanel>
</Grid>

I try to use this User Control from another control where I try to pass the parameter "name" to the previous UserControl ("Header").

I don't need to create a "ListBox" as I will only have 1 header, so I try to avoid doing:

            <ListBox x:Name="HeaderListBox" Grid.Row="0">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <SilverlightApplication:Header/>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

in order to send the "User" account using:

HeaderListBox.ItemsSource = name;

Is there any other structure I can use instead of the ListBox to pass the parameter just once? It won't be a list, it's just a header...

Thank you!

A: 

You can use the DataContext-Property on your UserControl directly:

<SilverlightApplication:Header DataContext="{Binding name}" />
gammelgul
+1  A: 

This code snippet won't do what you expect it to do.
The ListBox.ItemsSource needs to be a collection, sicne I assume "name" is of type String, the ListBox is really binding to a collection of chars.

Try changing the 2 following line to work with proper DataBinding:

1. HeaderListBox.ItemsSource = new string[] { name };
2. Text="{Binding}"

The first change is required so an ItemsControl (like ListBox) would be bound to multiple items, i.e. a collection.
The second change is required because there's no way the UserControl would know the property identifier "name", since you've just a assigned a value.

It seems like you're having basic issues with DataBinding, allow me to recommand you review some of the excellent reference material on Silverlight.net: http://www.silverlight.net/learn/quickstarts/bindingtocontrols/ http://www.silverlight.net/learn/videos/all/databinding-and-datatemplates-in-xaml
http://www.silverlight.net/learn/videos/all/an-overview-of-databinding-and-datatemplates-using-expression-blend
http://www.silverlight.net/learn/videos/all/databinding-to-control-properties

JustinAngel