Friday, 6 June 2008

WPF Example: Create UserControl and binding properties in a ListBox

see http://decav.com/blogs/andre/archive/2007/05/27/wpf-binding-to-properties-in-your-usercontrol-or-window.aspx

In order to bind the property, it needs to be a DependencyProperty, but not just that! You also need a control in XAML binding to your property. For example the following Control1 has a Message property:

XAML:

<UserControl x:Class="JSpike.Control1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="Control1Name">

<Grid>
<TextBlock x:Name="textBlock" Text="{Binding ElementName=Control1Name, Path=Message}"
Width="100" Height="25" Background="Aquamarine"></TextBlock>
</Grid>
</UserControl>

CS:

namespace JSpike
{
/// <summary>
/// Interaction logic for Control1.xaml
/// </summary>
public partial class Control1 : UserControl
{
public Control1()
{
InitializeComponent();
}

public static DependencyProperty MessageProperty = DependencyProperty.Register(
"Message", typeof(string), typeof(Control1));


public string Message
{
get
{
return (string)GetValue(MessageProperty);
}
set
{
SetValue(MessageProperty, value);
}

}
}

Now I want to bind this in a ListBox on Window1.xaml:


XAML:

<Window x:Class="JSpike.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:myCtrl="clr-namespace:JSpike"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<ObjectDataProvider x:Key="MyStringData"
ObjectType="{x:Type myCtrl:ListOfStuff}" MethodName="GetList" />

</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding Source={StaticResource MyStringData}}"
Margin="0,36,78,0">
<ListBox.ItemTemplate>
<DataTemplate>
<myCtrl:Control1 Message="{Binding Path=.}" Height="37"
HorizontalAlignment="Left" VerticalAlignment="Top" Width="105"></myCtrl:Control1>
</DataTemplate>
</ListBox.ItemTemplate>

</ListBox>
</Grid>
</Window>

Class ListOfStuff is the data provider:

namespace JSpike
{
class ListOfStuff
{
public List<string> GetList()
{
List<string> list = new List<string>();
list.Add("Hello");
list.Add("Goodbye");
list.Add("Heya");
list.Add("Cya");
return list;
}
}
}

Result:


image

6 comments:

  1. I get errors like "Name 'Control1Name' already exists in the current name scope" when i try to do this.

    ReplyDelete
  2. Maybe you do have a "Control1Name" exists in the same scope already?

    ReplyDelete
  3. This is great, thanks for posting. Any idea how to bind your custom control in a WrapPanel isntead of a ListBox? Thanks for the assistance!

    ReplyDelete
  4. Thanks, it helped me!

    ReplyDelete