Binding to current item, external collection management, DataTemplates and DataTriggers

5 במרץ 2008

אין תגובות

[This blog was migrated. You will not be able to comment here.
The new URL of this post is http://khason.net/blog/binding-to-current-item-external-collection-management-datatemplates-and-datatriggers/]


Today, we'll learn how to manage your collection, binded to ItemsControl externally, how to bind to the current item of the collection and how to use data templates with data triggers to make your UI data driven. So let's start.

image

First of all, we should create the items for the collection and the collection itself. IT's pretty straight-forward by now.

public class RedBlackItem : DependencyObject
    {
        public RedBlackItem(bool isRed)
        {
            this.IsRed = isRed;
        }

        public bool IsRed
        {
            get { return (bool)GetValue(IsRedProperty); }
            set { SetValue(IsRedProperty, value); }
        }
        public static readonly DependencyProperty IsRedProperty =
            DependencyProperty.Register("IsRed", typeof(bool), typeof(RedBlackItem), new UIPropertyMetadata(default(bool)));

    }

public class RedBlackCollection : ObservableCollection<RedBlackItem>
    {
        public RedBlackCollection()
        {
            Random r = new Random();
            for (int i = 0; i < 10; i++)
            {
                base.Add(new RedBlackItem(r.NextDouble() < 0.5));
            }
        }
    }

Next, let's create the instance of our collection in XAML and connect it to the view

<Window.Resources>
    <l:RedBlackCollection x:Key="collection"/>
    <CollectionViewSource Source="{StaticResource collection}" x:Key="data"/>

Actually, if you'll have at least one ItemsControl in your project, you not have to create CollectionView, due to fact, that Items is, actually will be the view. But we want it absolutely UI independent and data-driven, so we'll use CollectionViewSource to manage it.

Now, let's bind the collection view to our Item control

<ListBox ItemsSource="{Binding Source={StaticResource data}}"/>

Running the program right now, will display strings, reflecting the item type. Now we want to know what item was selected and display it in other place. But how to do it? We, actually, have no SelectedItem dependency property. Let try to make WPF to do all the work and bind the same collection to the control, that knows to display only one item. The best candidate for it is ContentControl

<ContentControl Content="{Binding Source={StaticResource data}}"/>

Compile and run. What's the magic. The control displays one item in our case it will be string, 'cos we have no template. Let's do it.

<DataTemplate DataType="{x:Type l:RedBlackItem}" x:Key="OtherTemplate">
    <Ellipse Width="100" Height="100">
            <Ellipse.Style>
                <Style>
                    <Setter Property="Ellipse.Fill" Value="Black"/>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=IsRed}" Value="True">
                            <Setter Property="Ellipse.Fill" Value="Red"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Ellipse.Style>
        </Ellipse>
</DataTemplate>

Fair enough. Simple data template, that uses ellipse with color fill, according the property of the item. Now, all we have to do is connect the template and the control. ContentTemplate property of ContentControl looks very good candidate for it.

<ContentControl ContentTemplate="{StaticResource OtherTemplate}" Content="{Binding Source={StaticResource data}}"/>

Now, let's make another data template (implicit in this case) to show our items in ListBox. We'll use DataTriggers to defer the color of each item.

<DataTemplate DataType="{x:Type l:RedBlackItem}">
            <Border BorderBrush="Blue" BorderThickness="1">
                <Border.Resources>
                    <Style TargetType="Rectangle">
                        <Setter Property="Fill" Value="Black"/>
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Path=IsRed}" Value="True">
                                <Setter Property="Fill" Value="Red"/>
                            </DataTrigger>
                         </Style.Triggers>
                    </Style>
                </Border.Resources>
                <Rectangle Width="100" Height="30"/>
            </Border>
        </DataTemplate>

Another thing we want to do is to detect selected item and put another filler for it. Smile in our case. Once, the items displayed by ListBoxItem, which is, actually ancestor of  our shape and have IsSelected dependency property, we can use relative source in DataTrigger to understand whether it selected or not. So fixing code like this will do the work

<DataTemplate DataType="{x:Type l:RedBlackItem}">
            <Border BorderBrush="Blue" BorderThickness="1">
                <Border.Resources>
                    <Style TargetType="Rectangle">
                        <Setter Property="Fill" Value="Black"/>
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Path=IsRed}" Value="True">
                                <Setter Property="Fill" Value="Red"/>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=ListBoxItem}, Path=IsSelected}" Value="True">
                                <Setter Property="Fill">
                                    <Setter.Value>
                                        <VisualBrush>
                                            <VisualBrush.Visual>
                                                <Path Fill="Black" Stroke="Yellow" StrokeThickness="1">
                                                    <Path.Data>
                                                        <GeometryGroup>
                                                            <EllipseGeometry Center="50,15" RadiusY="10" RadiusX="10"/>
                                                            <EllipseGeometry Center="45,13" RadiusY="3" RadiusX="3"/>
                                                            <EllipseGeometry Center="55,13" RadiusY="3" RadiusX="3"/>
                                                            <LineGeometry StartPoint="50,15" EndPoint="50,20"/>
                                                        </GeometryGroup>
                                                    </Path.Data>
                                                </Path>
                                            </VisualBrush.Visual>
                                        </VisualBrush>
                                    </Setter.Value>
                                </Setter>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </Border.Resources>
                <Rectangle Width="100" Height="30"/>
            </Border>
        </DataTemplate>

Now, when we can select items inside ItemsControl, we want to take it a bit far and select it by using control buttons. Let's make two RoutedCommand for this purpose and bind it by using command binding to our Window.

public static RoutedCommand MoveToPreviousCommand;
public static RoutedCommand MoveToNextCommand;

static Window1()
        {
            MoveToPreviousCommand = new RoutedCommand("MoveToPrevious", typeof(Window1));
            MoveToNextCommand = new RoutedCommand("MoveToNext", typeof(Window1));

            CommandManager.RegisterClassCommandBinding(typeof(Window1), new CommandBinding(MoveToPreviousCommand, ExecutedMoveCommand));
            CommandManager.RegisterClassCommandBinding(typeof(Window1), new CommandBinding(MoveToNextCommand, ExecutedMoveCommand));

        }

Inside the handler, we'll check what to do and use MoveToPreviouse/MoveToNext methods of collection view to manage it. Also, we want our collection to select first member, when we reach the end of it and last member, when we want one item before the first one. We might have all necessary information inside CollectionView to do it

static void ExecutedMoveCommand(object s, ExecutedRoutedEventArgs e)
        {
            Window1 w = s as Window1;
            if (e.Command == MoveToPreviousCommand)
            {
                w.data.View.MoveCurrentToPrevious();
                if (w.data.View.IsCurrentBeforeFirst)
                {
                    w.data.View.MoveCurrentToLast();
                }
            }
            else if (e.Command == MoveToNextCommand)
            {
                w.data.View.MoveCurrentToNext();
                if (w.data.View.IsCurrentAfterLast)
                {
                    w.data.View.MoveCurrentToFirst();
                }
            }
        }

All you have to do now is to create two RepeatButtons with nice vector arrows for back and forward to execute two of our commands and manage the collection

<RepeatButton Command="{x:Static l:Window1.MoveToPreviousCommand}"><Path Data="M1,1 L2,2 2,0 1,1"/></RepeatButton>
<RepeatButton Command="{x:Static l:Window1.MoveToNextCommand}"><Path Data="M2,1 L1,2 1,0 2,1"/></RepeatButton>

We done. A little facelifting and it's ready. Now we can know what item is selected by differing it inside it's visual presentation and data behind and viewing it as current item independently.

Thank you WPF for easy life. Be good people and learn a lot in Mix today.

Stay tuned for next days to my blog, In spite of the fact, that I'm not in Mix this year, I'm going to write about new beta version of Silverlight 2.0 with non-commercial go-life licence, small talk about XNA and my TechEd presentation, a bit about mobile development and other very cool things. Be sure to subscribe to my RSS feed for all this information.

Source code for this article

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. (*) שדות חובה מסומנים