Как я могу использовать ElementFlow?

Я относительно новичок в WPF, я работаю в фоновом режиме WinForms, пытаюсь реализовать прикрытие и не до конца понимаю пример. Из того, что я вижу, я добавляю пути к своим изображениям в StringCollection,

Вот что у меня сейчас:

public MainWindow()
{
    InitializeComponent();
    elementFlow1.Layout = new CoverFlow();
    StringCollection itemssource = new StringCollection();
    itemssource.Add(@"Images\1.png");
    itemssource.Add(@"Images\2.png");
    elementFlow1.SelectedIndex = 0;
    elementFlow1.ItemsSource = itemssource;
}

И у меня есть ElementFlow определяется в XAML следующим образом:

<fluidkit:ElementFlow Grid.Row="1" Height="194" Name="elementFlow1" VerticalAlignment="Top" Width="503" />

И вот, когда я запускаю его, ничего не происходит.

Может кто-нибудь объяснить, пожалуйста, как я должен использовать ElementFlow? Пример не очень "объясняет" это очень хорошо.

2 ответа

Вы пропускаете ключевой шаг. ElementFlow контрольные дисплеи UIElementс, а не строки. У вас есть список строк, которые содержат логическое расположение файлов изображений. Теперь вам нужно преобразовать эту коллекцию строк в коллекцию DataTemplates. Если вы посмотрите в пример файла xaml, вы увидите этот раздел:

<DataTemplate x:Key="TestDataTemplate"
                  DataType="{x:Type sys:String}">
        <Border x:Name="ElementVisual"
                Background="White"
                Padding="5"
                BorderThickness="5"
                BorderBrush="LightGray"
                Grid.Row="0">
            <Image Source="{Binding}"
                   Stretch="Fill" />
        </Border>
    </DataTemplate>

Этот раздел, по сути, принимает строку ввода и преобразует его в DataTemplate, Это делается путем установки ItemTemplate свойство к этому DataTemplate ресурс.

Вам, вероятно, будет лучше манипулировать этим элементом управления в XAML, а не кодом. Так проще (по-моему, в любом случае).

Надеюсь это поможет.

Я бы рекомендовал следующие примеры:

http://fluidkit.codeplex.com/SourceControl/latest

Это мой мод, проект с именем: ElementFlowExample

namespace ElementFlowExample
{



#region Using Statements:



using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Navigation;
using System.Windows.Shapes;

using FluidKit.Controls;
using FluidKit.Showcase.ElementFlow;



#endregion




/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{



    #region Fields:


    private StringCollection _dataSource;

    private LayoutBase[] _layouts = {
                                        new Wall(),
                                        new SlideDeck(),
                                        new CoverFlow(),
                                        new Carousel(),
                                        new TimeMachine2(),
                                        new ThreeLane(),
                                        new VForm(),
                                        new TimeMachine(),
                                        new RollerCoaster(),
                                        new Rolodex(),
                                    };

    private Random _randomizer = new Random();

    private int _viewIndex;


    #endregion




    #region Properties:


    #endregion




    public MainWindow()
    {
        InitializeComponent();
    }




    private void Window_Loaded(object sender, RoutedEventArgs e)
    {

        _elementFlow.Layout = _layouts[3];
        _currentViewText.Text = _elementFlow.Layout.GetType().Name;

        _selectedIndexSlider.Maximum = _elementFlow.Items.Count - 1;
        _elementFlow.SelectionChanged += EFSelectedIndexChanged;
        _elementFlow.SelectedIndex = 0;

        _dataSource = FindResource("DataSource") as StringCollection;


    }




    private void EFSelectedIndexChanged(object sender, SelectionChangedEventArgs e)
    {
        Debug.WriteLine((sender as ElementFlow).SelectedIndex);
    }




    protected override void OnKeyDown(KeyEventArgs e)
    {
        if (e.Key == Key.F12)
        {
            _viewIndex = (_viewIndex + 1) % _layouts.Length;
            _elementFlow.Layout = _layouts[_viewIndex];
            _currentViewText.Text = _elementFlow.Layout.GetType().Name;
        }
    }




    private void ChangeSelectedIndex(object sender, RoutedPropertyChangedEventArgs<double> args)
    {
        _elementFlow.SelectedIndex = (int)args.NewValue;
    }




    private void RemoveCard(object sender, RoutedEventArgs args)
    {
        if (_elementFlow.Items.Count > 0)
        {
            _dataSource.RemoveAt(_randomizer.Next(_dataSource.Count));

            // Update selectedindex slider
            _selectedIndexSlider.Maximum = _elementFlow.Items.Count - 1;
        }
    }




    private void AddCard(object sender, RoutedEventArgs args)
    {
        Button b = sender as Button;
        int index = _randomizer.Next(_dataSource.Count);
        if (b.Name == "_regular")
        {
            _dataSource.Insert(index, "Images/01.jpg");
        }
        else
        {
            _dataSource.Insert(index, string.Format("Images/{0:00}", _randomizer.Next(1, 12)) + ".jpg");
        }

        // Update selectedindex slider
        _selectedIndexSlider.Maximum = _elementFlow.Items.Count - 1;
    }




} // END of Class...

} // END of Namespace...

<Window x:Class="ElementFlowExample.MainWindow"
        xmlns:b="clr-namespace:ElementFlowExample"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
  xmlns:local="clr-namespace:FluidKit.Showcase.ElementFlow"
  xmlns:Controls="clr-namespace:FluidKit.Controls;assembly=FluidKit"
                
        Loaded="Window_Loaded"
        Title="ElementFlow - FluidKit"
  WindowStartupLocation="CenterScreen"
        Width="1280"
        Height="720">


    <Window.Resources>

        <local:StringCollection x:Key="DataSource" />

        <LinearGradientBrush x:Key="ReflectionBrush" StartPoint="0,0" EndPoint="0,1">
            <GradientStop Offset="0" Color="#7F000000" />
            <GradientStop Offset=".5" Color="Transparent" />
        </LinearGradientBrush>



        <DataTemplate x:Key="TestDataTemplate"
                      DataType="{x:Type sys:String}">
            <Border x:Name="ElementVisual"
                    Background="White"
                    Padding="5"
                    BorderThickness="5"
                    BorderBrush="LightGray"
                    Grid.Row="0">
                <Image Source="{Binding}"
                       Stretch="Fill" />
            </Border>
        </DataTemplate>



        <DataTemplate x:Key="TestDataTemplate_Reflection">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="0.5*" />
                    <RowDefinition Height="0.5*" />
                </Grid.RowDefinitions>

                <Border x:Name="ElementVisual"
                        BorderThickness="2"
                        BorderBrush="LightYellow"
                        Background="Black"
                        Padding="2">
                    <Image Source="{Binding}"
                           Stretch="Fill" />
                </Border>
                <Rectangle OpacityMask="{StaticResource ReflectionBrush}"
                           Grid.Row="1"
                           Height="{Binding ActualHeight, ElementName=ElementVisual}">
                    <Rectangle.Fill>
                        <VisualBrush Visual="{Binding ElementName=ElementVisual}">
                            <VisualBrush.RelativeTransform>
                                <ScaleTransform ScaleX="1"
                                                ScaleY="-1"
                                                CenterX="0.5"
                                                CenterY="0.5" />
                            </VisualBrush.RelativeTransform>
                        </VisualBrush>
                    </Rectangle.Fill>
                </Rectangle>
            </Grid>
        </DataTemplate>
        <DataTemplate x:Key="ItemTemplate">
            <Border BorderBrush="#FFB1B1B1"
                    BorderThickness="2"
                    Background="#7FFFFFFF"
                    Padding="0,20,0,0"
                    CornerRadius="3">
                <Image Source="{Binding Image}"
                       HorizontalAlignment="Left"
                       VerticalAlignment="Top"
                       Stretch="Fill" />
            </Border>
        </DataTemplate>


    </Window.Resources>

    <Grid>


        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="0.5*" />
            <ColumnDefinition Width="0.5*" />
        </Grid.ColumnDefinitions>


        <StackPanel Orientation="Vertical"
                    Grid.Row="1"
                    Grid.Column="0"
                    Margin="5">
            <Label Content="SelectedIndex" />
            <Slider x:Name="_selectedIndexSlider"
                    Minimum="0"
                    Value="0"
                    ValueChanged="ChangeSelectedIndex" />
            <Label Content="TiltAngle" />
            <Slider x:Name="_tiltAngleSlider"
                    Minimum="0"
                    Maximum="90"
                    Value="45" />
            <Label Content="ItemGap" />
            <Slider x:Name="_itemGapSlider"
                    Minimum="0.25"
                    Maximum="3"
                    Value="0.65" />
        </StackPanel>

        <StackPanel Orientation="Vertical"
                    Grid.Row="1"
                    Grid.Column="1"
                    Margin="5">
            <Label Content="FrontItemGap" />
            <Slider x:Name="_frontItemGapSlider"
                    Minimum="0"
                    Maximum="4.0" 
                    Value="1.5"/>
            <Label Content="PopoutDistance" />
            <Slider x:Name="_popoutDistanceSlider"
                    Minimum="-2.0"
                    Maximum="2.0"
                    Value="-0.3" />
            <StackPanel Orientation="Horizontal"
                        Margin="0,10,0,0">

                <Button x:Name="_regular"
                        Click="AddCard"
                        Margin="0,0,10,0"
                        Content="Add Type A" />
                <Button x:Name="_alert"
                        Click="AddCard"
                        Margin="0,0,10,0"
                        Content="Add Type B" />
                <Button Click="RemoveCard"
                        Margin="0,0,10,0"
                        Content="Remove" />
            </StackPanel>
        </StackPanel>



        <Controls:ElementFlow x:Name="_elementFlow"
                              Grid.Row="0"
                              Grid.Column="0"
                              Grid.ColumnSpan="2"
                              ItemsSource="{DynamicResource DataSource}"
                              ItemTemplate="{DynamicResource TestDataTemplate}"
                              TiltAngle="{Binding Value, ElementName=_tiltAngleSlider}"
                              ItemGap="{Binding Value, ElementName=_itemGapSlider}"
                              FrontItemGap="{Binding Value, ElementName=_frontItemGapSlider}"
                              PopoutDistance="{Binding Value, ElementName=_popoutDistanceSlider}"
                              ElementWidth="300"
                              ElementHeight="200"
                              SelectedIndex="3">
            <Controls:ElementFlow.Layout>
                <Controls:CoverFlow />
            </Controls:ElementFlow.Layout>
            <Controls:ElementFlow.Background>
                <LinearGradientBrush EndPoint="0.5,1"
                                     StartPoint="0.5,0">
                    <GradientStop Color="#FF181818" />
                    <GradientStop Color="#FF7A7A7A"
                                  Offset="0.5" />
                    <GradientStop Color="#FF1A1A1A"
                                  Offset="1" />
                </LinearGradientBrush>
            </Controls:ElementFlow.Background>
            <Controls:ElementFlow.Camera>
                <PerspectiveCamera FieldOfView="60"
                                   Position="0,3,6"
                                   LookDirection="0,-3,-6" />
            </Controls:ElementFlow.Camera>
        </Controls:ElementFlow>

        <TextBlock Text="F12 to switch views"
                   Foreground="White"
                   FontWeight="Bold"
                   VerticalAlignment="Top"
                   HorizontalAlignment="Right"
                   Margin="10"
                   Grid.Row="0"
                   Grid.Column="1" />

        <TextBlock x:Name="_currentViewText"
                   Foreground="White"
                   FontWeight="Bold"
                   VerticalAlignment="Top"
                   HorizontalAlignment="Right"
                   Margin="10,30,10,10"
                   Grid.Row="0"
                   Grid.Column="1" />
    </Grid>


</Window>
    
    

Надеюсь это поможет!

Другие вопросы по тегам