/// <summary>
        /// Default constructor builds a ComboBox inline editor template.
        /// </summary>
        public CultureInfoEditor()
        {
            // not using databinding here because Silverlight does not support
            // the WPF CultureConverter that is used by Blend.
            FrameworkElementFactory comboBox = new FrameworkElementFactory(typeof(ComboBox));
            comboBox.AddHandler(
                ComboBox.LoadedEvent,
                new RoutedEventHandler(
                    (sender, e) =>
                    {
                        _owner = (ComboBox)sender;
                        _owner.SelectionChanged += EditorSelectionChanged;
                        INotifyPropertyChanged data = _owner.DataContext as INotifyPropertyChanged;
                        if (data != null)
                        {
                            data.PropertyChanged += DatacontextPropertyChanged;
                        }
                        _owner.DataContextChanged += CultureDatacontextChanged;
                    }));

            comboBox.SetValue(ComboBox.IsEditableProperty, false);
            comboBox.SetValue(ComboBox.DisplayMemberPathProperty, "DisplayName");
            comboBox.SetValue(ComboBox.ItemsSourceProperty, CultureInfo.GetCultures(CultureTypes.SpecificCultures));
            DataTemplate dt = new DataTemplate();
            dt.VisualTree = comboBox;

            InlineEditorTemplate = dt;
        }
 /// <summary>
 /// Default constructor builds the default TextBox inline editor template.
 /// </summary>
 public EmptyEditor()
 {
     FrameworkElementFactory textBox = new FrameworkElementFactory(typeof(TextBox));
     textBox.SetValue(TextBox.IsReadOnlyProperty, true);
     DataTemplate dt = new DataTemplate();
     dt.VisualTree = textBox;
     InlineEditorTemplate = dt;
 }
        static TreeViewEx()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(TreeViewEx), new FrameworkPropertyMetadata(typeof(TreeViewEx)));

            FrameworkElementFactory vPanel = new FrameworkElementFactory(typeof(VirtualizingTreePanel));
            vPanel.SetValue(VirtualizingTreePanel.IsItemsHostProperty, true);
            ItemsPanelTemplate vPanelTemplate = new ItemsPanelTemplate();
            vPanelTemplate.VisualTree = vPanel;
            ItemsPanelProperty.OverrideMetadata(typeof(TreeViewEx), new FrameworkPropertyMetadata(vPanelTemplate));

            KeyboardNavigation.DirectionalNavigationProperty.OverrideMetadata(typeof(TreeViewEx), new FrameworkPropertyMetadata(KeyboardNavigationMode.Contained));
            KeyboardNavigation.TabNavigationProperty.OverrideMetadata(typeof(TreeViewEx), new FrameworkPropertyMetadata(KeyboardNavigationMode.None));
        }
Exemple #4
0
		public EditableTextBlock()
		{
			var textBox = new FrameworkElementFactory(typeof(TextBox));
			textBox.SetValue(Control.PaddingProperty, new Thickness(1)); // 1px for border
			textBox.AddHandler(FrameworkElement.LoadedEvent, new RoutedEventHandler(TextBox_Loaded));
			textBox.AddHandler(UIElement.KeyDownEvent, new KeyEventHandler(TextBox_KeyDown));
			textBox.AddHandler(UIElement.LostFocusEvent, new RoutedEventHandler(TextBox_LostFocus));
			textBox.SetBinding(TextBox.TextProperty, new Windows.UI.Xaml.Data.Binding("Text") { Source = this, Mode = BindingMode.TwoWay
#if TODO_XAML
				, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged 
#endif
			});
			var editTemplate = new DataTemplate { VisualTree = textBox };

			var textBlock = new FrameworkElementFactory(typeof(TextBlock));
			textBlock.SetValue(FrameworkElement.MarginProperty, new Thickness(2));
			textBlock.AddHandler(UIElement.PointerPressedEvent, (s, e) => {
				PointerPoint pt;
				if (e.Pointer.PointerDeviceType == PointerDeviceType.Mouse &&
					(pt = e.GetCurrentPoint(textBlock) != null) &&
#if TODO_XAML
					e.ClickCount >= 2 &&
#endif
					pt.Properties.IsLeftButtonPressed)
				{
					IsInEditMode = true;
					e.Handled = true;
				}

			});
			textBlock.SetBinding(TextBlock.TextProperty, new Windows.UI.Xaml.Data.Binding("Text") { Source = this });
			var viewTemplate = new DataTemplate { VisualTree = textBlock };

			var style = new Windows.UI.Xaml.Style(typeof(EditableTextBlock));
			var trigger = new Trigger { Property = IsInEditModeProperty, Value = true };
			trigger.Setters.Add(new Setter { Property = ContentTemplateProperty, Value = editTemplate });
			style.Triggers.Add(trigger);

			trigger = new Trigger { Property = IsInEditModeProperty, Value = false };
			trigger.Setters.Add(new Setter { Property = ContentTemplateProperty, Value = viewTemplate });
			style.Triggers.Add(trigger);
			Style = style;
		}
Exemple #5
0
        /// <summary>
        ///     Instantiates global information.
        /// </summary>
        static DataGrid()
        {
            Type ownerType = typeof(DataGrid);

            DefaultStyleKeyProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(typeof(DataGrid)));
            FrameworkElementFactory dataGridRowPresenterFactory = new FrameworkElementFactory(typeof(DataGridRowsPresenter));
            dataGridRowPresenterFactory.SetValue(FrameworkElement.NameProperty, ItemsPanelPartName);
            ItemsPanelProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(new ItemsPanelTemplate(dataGridRowPresenterFactory)));
            VirtualizingPanel.IsVirtualizingProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(true, null, new CoerceValueCallback(OnCoerceIsVirtualizingProperty)));
            VirtualizingPanel.VirtualizationModeProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(VirtualizationMode.Recycling));
            ItemContainerStyleProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(null, new CoerceValueCallback(OnCoerceItemContainerStyle)));
            ItemContainerStyleSelectorProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(null, new CoerceValueCallback(OnCoerceItemContainerStyleSelector)));
            ItemsSourceProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata((PropertyChangedCallback)null, OnCoerceItemsSourceProperty));
            AlternationCountProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(0, null, new CoerceValueCallback(OnCoerceAlternationCount)));
            IsEnabledProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(new PropertyChangedCallback(OnIsEnabledChanged)));
            IsKeyboardFocusWithinPropertyKey.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(new PropertyChangedCallback(OnIsKeyboardFocusWithinChanged)));
            IsSynchronizedWithCurrentItemProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(null, new CoerceValueCallback(OnCoerceIsSynchronizedWithCurrentItem)));
            IsTabStopProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(false));
            KeyboardNavigation.DirectionalNavigationProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(KeyboardNavigationMode.Contained));
            KeyboardNavigation.ControlTabNavigationProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(KeyboardNavigationMode.Once));

            CommandManager.RegisterClassInputBinding(ownerType, new InputBinding(BeginEditCommand, new KeyGesture(Key.F2)));
            CommandManager.RegisterClassCommandBinding(ownerType, new CommandBinding(BeginEditCommand, new ExecutedRoutedEventHandler(OnExecutedBeginEdit), new CanExecuteRoutedEventHandler(OnCanExecuteBeginEdit)));

            CommandManager.RegisterClassCommandBinding(ownerType, new CommandBinding(CommitEditCommand, new ExecutedRoutedEventHandler(OnExecutedCommitEdit), new CanExecuteRoutedEventHandler(OnCanExecuteCommitEdit)));

            CommandManager.RegisterClassInputBinding(ownerType, new InputBinding(CancelEditCommand, new KeyGesture(Key.Escape)));
            CommandManager.RegisterClassCommandBinding(ownerType, new CommandBinding(CancelEditCommand, new ExecutedRoutedEventHandler(OnExecutedCancelEdit), new CanExecuteRoutedEventHandler(OnCanExecuteCancelEdit)));

            CommandManager.RegisterClassCommandBinding(ownerType, new CommandBinding(SelectAllCommand, new ExecutedRoutedEventHandler(OnExecutedSelectAll), new CanExecuteRoutedEventHandler(OnCanExecuteSelectAll)));

            CommandManager.RegisterClassCommandBinding(ownerType, new CommandBinding(DeleteCommand, new ExecutedRoutedEventHandler(OnExecutedDelete), new CanExecuteRoutedEventHandler(OnCanExecuteDelete)));

            // Default Clipboard handling
            CommandManager.RegisterClassCommandBinding(typeof(DataGrid), new CommandBinding(ApplicationCommands.Copy, new ExecutedRoutedEventHandler(OnExecutedCopy), new CanExecuteRoutedEventHandler(OnCanExecuteCopy)));

            EventManager.RegisterClassHandler(typeof(DataGrid), MouseUpEvent, new MouseButtonEventHandler(OnAnyMouseUpThunk), true);
        }
Exemple #6
0
        public MainWindow(bool IsAdmin)
        {
            var articles = new List <Article>();
            var changes  = new List <Change>();

            var dataFile = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "Data.txt");
            var data     = dataFile.ReadToEnd().Split('c');

            dataFile.Close();
            var articleIndex = data[0].Split(',');
            var changesIndex = data[1].Split(',').Where(x => !IsNullOrWhiteSpace(x));

            foreach (var index in articleIndex)
            {
                articles.Add(Article.ReadArticle("Article" + index + ".txt", int.Parse(index)));
            }
            articles.Sort((a1, a2) => Compare(a1.Header, a2.Header, StringComparison.Ordinal));

            foreach (var index in changesIndex)
            {
                changes.Add(Change.ReadChange("Change" + index + ".txt", int.Parse(index)));
            }
            changes.Sort((a1, a2) => Compare(a1.Header, a2.Header, StringComparison.Ordinal));

            InitializeComponent();

            layoutGrid.Background    = Brushes.White;
            layoutGrid.ShowGridLines = true;

            var leftCol = new ColumnDefinition {
                Width = new GridLength(300, GridUnitType.Pixel)
            };
            var rightCol = new ColumnDefinition {
                Width = new GridLength(1, GridUnitType.Star)
            };

            layoutGrid.ColumnDefinitions.Add(leftCol);
            layoutGrid.ColumnDefinitions.Add(rightCol);

            #region Левая часть

            var leftScroll = new ScrollViewer
            {
                VerticalScrollBarVisibility   = ScrollBarVisibility.Auto,
                HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,
                Height = IsAdmin ? 960 : 1020
            };
            Grid.SetColumn(leftScroll, 0);
            Grid.SetRow(leftScroll, 0);

            var leftStackPanel = new StackPanel
            {
                HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top
            };
            Grid.SetColumn(leftStackPanel, 0);
            Grid.SetRow(leftStackPanel, 0);

            var listElement = new DataTemplate {
                DataType = typeof(Article)
            };
            var spFactory = new FrameworkElementFactory(typeof(StackPanel))
            {
                Name = "myComboFactory"
            };
            spFactory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
            var title = new FrameworkElementFactory(typeof(TextBlock));
            title.SetBinding(TextBlock.TextProperty, new Binding(""));
            title.SetValue(TextBlock.FontSizeProperty, 20.0);
            title.SetValue(TextBlock.TextWrappingProperty, TextWrapping.Wrap);
            title.SetValue(TextBlock.WidthProperty, 280.0);
            spFactory.AppendChild(title);
            listElement.VisualTree = spFactory;

            var listBox = new ListBox
            {
                HorizontalAlignment = HorizontalAlignment.Stretch,
                Margin        = new Thickness(0), Width = 300,
                ItemsSource   = articles, ItemTemplate = listElement,
                SelectionMode = SelectionMode.Single
            };

            var articlesButton = new Button
            {
                VerticalAlignment   = VerticalAlignment.Bottom,
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin  = new Thickness(0),
                Height  = 30, Width = 300,
                Content = "Конспекты", FontSize = 15
            };
            articlesButton.Click += (v, e) =>
            {
                listBox.ItemsSource = articles;
                InvalidateVisual();
            };

            var changesButton = new Button
            {
                VerticalAlignment   = VerticalAlignment.Bottom,
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin  = new Thickness(0),
                Height  = 30, Width = 300,
                Content = "Правки", FontSize = 15
            };
            changesButton.Click += (v, e) =>
            {
                listBox.ItemsSource = changes;
                InvalidateVisual();
            };

            leftScroll.Content = listBox;
            leftStackPanel.Children.Add(leftScroll);
            if (IsAdmin)
            {
                leftStackPanel.Children.Add(articlesButton);
                leftStackPanel.Children.Add(changesButton);
            }

            #endregion

            #region Правая часть

            var rightStackPanel = new StackPanel
            {
                HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top
            };
            Grid.SetColumn(rightStackPanel, 1);
            Grid.SetRow(rightStackPanel, 0);

            var titleTextBlock = new TextBlock
            {
                FontSize            = 30, Margin = new Thickness(0),
                FontWeight          = FontWeights.Bold,
                HorizontalAlignment = HorizontalAlignment.Center,
                Text = "Выберите конспект", TextWrapping = TextWrapping.Wrap
            };

            var rightScroll = new ScrollViewer
            {
                VerticalScrollBarVisibility   = ScrollBarVisibility.Auto,
                HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,
                Height = 945, Margin = new Thickness(0)
            };
            Grid.SetColumn(rightScroll, 1);
            Grid.SetRow(rightScroll, 0);

            var contentTextBlock = new TextBlock
            {
                Margin              = new Thickness(10, 10, 10, 0),
                FontSize            = 15, FontWeight = FontWeights.Normal,
                HorizontalAlignment = HorizontalAlignment.Center,
                TextWrapping        = TextWrapping.Wrap
            };

            var contentTextBox = new TextBox
            {
                Margin                     = new Thickness(10, 10, 10, 0),
                FontSize                   = 15, Width = 1620,
                HorizontalAlignment        = HorizontalAlignment.Center,
                HorizontalContentAlignment = HorizontalAlignment.Center,
                TextWrapping               = TextWrapping.Wrap, AcceptsReturn = true
            };

            var changingButton = new Button
            {
                VerticalAlignment   = VerticalAlignment.Bottom,
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin   = new Thickness(0),
                Height   = 40, Width = 1620, Content = "Предложить правку",
                FontSize = 18, IsEnabled = false
            };

            var sendChangesButton = new Button
            {
                VerticalAlignment   = VerticalAlignment.Bottom,
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin   = new Thickness(0),
                Height   = 40, Width = 1620, Content = "Отправить правку",
                FontSize = 18, IsEnabled = false
            };


            var acceptChangesButton = new Button
            {
                VerticalAlignment   = VerticalAlignment.Bottom,
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin    = new Thickness(0),
                Height    = 40, Width = 1620, Content = "Принять правку",
                IsEnabled = false, FontSize = 18
            };

            rightStackPanel.Children.Add(titleTextBlock);
            rightScroll.Content = contentTextBlock;
            rightStackPanel.Children.Add(rightScroll);
            rightStackPanel.Children.Add(listBox.ItemsSource == articles ? changingButton : acceptChangesButton);

            #endregion

            listBox.SelectionChanged += (v, e) =>
            {
                rightScroll.Content = contentTextBlock;
                rightStackPanel.Children.Clear();
                rightStackPanel.Children.Add(titleTextBlock);
                rightStackPanel.Children.Add(rightScroll);
                changingButton.IsEnabled      = false;
                sendChangesButton.IsEnabled   = false;
                acceptChangesButton.IsEnabled = false;
                if (listBox.SelectedIndex != -1)
                {
                    if (listBox.ItemsSource == articles)
                    {
                        titleTextBlock.Text      = articles.ElementAt(listBox.SelectedIndex).Header;
                        contentTextBlock.Text    = articles.ElementAt(listBox.SelectedIndex).Content;
                        changingButton.IsEnabled = true;
                        rightStackPanel.Children.Add(changingButton);
                    }
                    else
                    {
                        titleTextBlock.Text           = changes.ElementAt(listBox.SelectedIndex).Header;
                        contentTextBlock.Text         = changes.ElementAt(listBox.SelectedIndex).Content;
                        acceptChangesButton.IsEnabled = true;
                        rightStackPanel.Children.Add(acceptChangesButton);
                    }
                }
                InvalidateVisual();
            };

            changingButton.Click += (v, e) =>
            {
                contentTextBox.Text = articles.ElementAt(listBox.SelectedIndex).Content;
                rightScroll.Content = contentTextBox;
                rightStackPanel.Children.Clear();
                rightStackPanel.Children.Add(titleTextBlock);
                rightStackPanel.Children.Add(rightScroll);
                rightStackPanel.Children.Add(sendChangesButton);
                InvalidateVisual();
            };

            contentTextBox.GotKeyboardFocus += (v, e) =>
            {
                sendChangesButton.IsEnabled = true;
                InvalidateVisual();
            };

            sendChangesButton.Click += (v, e) =>
            {
                var warning = MessageBox.Show("Вы точно хотите предложить правку?", "Подтверждение",
                                              MessageBoxButton.YesNo, MessageBoxImage.Question);
                switch (warning)
                {
                case MessageBoxResult.Yes:
                    rightScroll.Content = contentTextBlock;
                    rightStackPanel.Children.Clear();
                    rightStackPanel.Children.Add(titleTextBlock);
                    rightStackPanel.Children.Add(rightScroll);
                    rightStackPanel.Children.Add(changingButton);
                    InvalidateVisual();
                    var article = listBox.SelectedItem as Article;
                    Change.CreateChange(
                        titleTextBlock.Text + "'" + article.Index + "'" +
                        contentTextBox.Text,
                        changes.Count + 1);
                    changes.Add(new Change(article.Index, changes.Count + 1, titleTextBlock.Text, contentTextBox.Text));
                    changes.Sort((a1, a2) => Compare(a1.Header, a2.Header, StringComparison.Ordinal));
                    break;

                case MessageBoxResult.No:
                    break;
                }
            };

            acceptChangesButton.Click += (v, e) =>
            {
                var warning = MessageBox.Show("Вы точно хотите принять правку?", "Подтверждение",
                                              MessageBoxButton.YesNo, MessageBoxImage.Question);
                switch (warning)
                {
                case MessageBoxResult.Yes:
                    var change = listBox.SelectedItem as Change;
                    Change.AcceptChange(change.Index);
                    var changedArtcle = articles.Find(x => x.Index == (change.Index - 1));
                    changedArtcle.Header  = titleTextBlock.Text;
                    changedArtcle.Content = contentTextBlock.Text;
                    changes.RemoveAt(changes.FindIndex(a => a.Header.StartsWith(titleTextBlock.Text)));
                    titleTextBlock.Text   = "Выберите правку";
                    contentTextBlock.Text = "";
                    contentTextBox.Text   = "";
                    break;

                case MessageBoxResult.No:
                    break;
                }
                rightStackPanel.Children.Clear();
                titleTextBlock.Text   = "Выберите правку";
                contentTextBlock.Text = "";
                contentTextBox.Text   = "";
                rightStackPanel.Children.Add(titleTextBlock);
                rightStackPanel.Children.Add(rightScroll);
                rightStackPanel.Children.Add(acceptChangesButton);
                InvalidateVisual();
            };

            articlesButton.Click += (v, e) =>
            {
                rightStackPanel.Children.Clear();
                titleTextBlock.Text   = "Выберите конспект";
                contentTextBlock.Text = "";
                contentTextBox.Text   = "";
                rightStackPanel.Children.Add(titleTextBlock);
                rightStackPanel.Children.Add(rightScroll);
                rightStackPanel.Children.Add(changingButton);
                InvalidateVisual();
            };
            changesButton.Click += (v, e) =>
            {
                rightStackPanel.Children.Clear();
                titleTextBlock.Text   = "Выберите правку";
                contentTextBlock.Text = "";
                contentTextBox.Text   = "";
                rightStackPanel.Children.Add(titleTextBlock);
                rightStackPanel.Children.Add(rightScroll);
                rightStackPanel.Children.Add(acceptChangesButton);
                InvalidateVisual();
            };

            layoutGrid.Children.Add(leftStackPanel);
            layoutGrid.Children.Add(rightStackPanel);
        }
        // Create the indicator for column re-ordering
        private void AddIndicator()
        {
            Separator indicator = new Separator();
            indicator.Visibility = Visibility.Hidden;

            // Indicator style:
            //
            // <Setter Property="Margin" Value="0" />
            // <Setter Property="Width" Value="2" />
            // <Setter Property="Template">
            //   <Setter.Value>
            //     <ControlTemplate TargetType="{x:Type Separator}">
            //        <Border Background="#FF000080"/>
            //     </ControlTemplate>
            //   </Setter.Value>
            // </Setter>

            indicator.Margin = new Thickness(0);
            indicator.Width = 2.0;

            FrameworkElementFactory border = new FrameworkElementFactory(typeof(Border));
            border.SetValue(Border.BackgroundProperty, new SolidColorBrush(Color.FromUInt32(0xFF000080)));

            ControlTemplate template = new ControlTemplate(typeof(Separator));
            template.VisualTree = border;
            template.Seal();

            indicator.Template = template;

            InternalChildren.AddInternal(indicator);
            _indicator = indicator;
        }
Exemple #8
0
        public override void Load(NetworkLogViewerBase viewer)
        {
            if (m_viewer != null)
            {
                throw new InvalidOperationException();
            }

            m_viewer = viewer;
            viewer.ItemVisualDataQueried += m_itemVisualDataQueriedHandler;

            var view = m_view = new GridView();

            var nColumns = s_columnWidths.Length;
            var headers  = new string[]
            {
                NetworkStrings.CH_Number,
                NetworkStrings.CH_Time,
                NetworkStrings.CH_Ticks,
                NetworkStrings.CH_C2S,
                NetworkStrings.CH_S2C,
                NetworkStrings.CH_Length,
            };

            if (headers.Length != nColumns)
            {
                throw new InvalidOperationException();
            }

            double[] widths = Configuration.GetValue("Column Widths", (double[])null);
            if (widths == null || widths.Length != nColumns)
            {
                widths = s_columnWidths;
            }

            int[] columnOrder = Configuration.GetValue("Column Order", (int[])null);
            if (columnOrder == null || columnOrder.Length != nColumns ||
                columnOrder.Any(val => val >= nColumns || val < 0))
            {
                columnOrder = Enumerable.Range(0, nColumns).ToArray();
            }

            for (int i = 0; i < nColumns; i++)
            {
                int col = columnOrder[i];

                var item = new GridViewColumnWithId();
                item.ColumnId = col;
                item.Header   = headers[col];
                item.Width    = widths[col];

                var dataTemplate = new DataTemplate();
                dataTemplate.DataType = typeof(ItemVisualData);

                var block = new FrameworkElementFactory(typeof(TextBlock));
                block.SetValue(TextBlock.TextProperty, new Binding(s_columnBindings[col]));

                dataTemplate.VisualTree = block;
                item.CellTemplate       = dataTemplate;

                view.Columns.Add(item);
            }
        }
        private static void CreateDragAdorner()
        {
            var template         = GetDragAdornerTemplate(m_DragInfo.VisualSource);
            var templateSelector = GetDragAdornerTemplateSelector(m_DragInfo.VisualSource);

            UIElement adornment = null;

            var useDefaultDragAdorner = GetUseDefaultDragAdorner(m_DragInfo.VisualSource);

            if (template == null && templateSelector == null && useDefaultDragAdorner)
            {
                var bs = CaptureScreen(m_DragInfo.VisualSourceItem, m_DragInfo.VisualSourceFlowDirection);
                if (bs != null)
                {
                    var factory = new FrameworkElementFactory(typeof(Image));
                    factory.SetValue(Image.SourceProperty, bs);
                    factory.SetValue(RenderOptions.EdgeModeProperty, EdgeMode.Aliased);
                    factory.SetValue(RenderOptions.BitmapScalingModeProperty, BitmapScalingMode.HighQuality);
                    factory.SetValue(FrameworkElement.WidthProperty, bs.Width);
                    factory.SetValue(FrameworkElement.HeightProperty, bs.Height);
                    factory.SetValue(FrameworkElement.HorizontalAlignmentProperty, HorizontalAlignment.Left);
                    factory.SetValue(FrameworkElement.VerticalAlignmentProperty, VerticalAlignment.Top);
                    template = new DataTemplate {
                        VisualTree = factory
                    };
                }
            }

            if (template != null || templateSelector != null)
            {
                if (m_DragInfo.Data is IEnumerable && !(m_DragInfo.Data is string))
                {
                    if (!useDefaultDragAdorner && ((IEnumerable)m_DragInfo.Data).Cast <object>().Count() <= 10)
                    {
                        var itemsControl = new ItemsControl();
                        itemsControl.ItemsSource          = (IEnumerable)m_DragInfo.Data;
                        itemsControl.ItemTemplate         = template;
                        itemsControl.ItemTemplateSelector = templateSelector;

                        // The ItemsControl doesn't display unless we create a border to contain it.
                        // Not quite sure why this is...
                        var border = new Border();
                        border.Child = itemsControl;
                        adornment    = border;
                    }
                }
                else
                {
                    var contentPresenter = new ContentPresenter();
                    contentPresenter.Content                 = m_DragInfo.Data;
                    contentPresenter.ContentTemplate         = template;
                    contentPresenter.ContentTemplateSelector = templateSelector;
                    adornment = contentPresenter;
                }
            }

            if (adornment != null)
            {
                if (useDefaultDragAdorner)
                {
                    adornment.Opacity = GetDefaultDragAdornerOpacity(m_DragInfo.VisualSource);
                }

                var parentWindow = m_DragInfo.VisualSource.GetVisualAncestor <Window>();
                var rootElement  = parentWindow != null ? parentWindow.Content as UIElement : null;
                if (rootElement == null && Application.Current != null && Application.Current.MainWindow != null)
                {
                    rootElement = (UIElement)Application.Current.MainWindow.Content;
                }
                //                i don't want the fu... windows forms reference
                //                if (rootElement == null) {
                //                    var elementHost = m_DragInfo.VisualSource.GetVisualAncestor<ElementHost>();
                //                    rootElement = elementHost != null ? elementHost.Child : null;
                //                }
                if (rootElement == null)
                {
                    rootElement = m_DragInfo.VisualSource.GetVisualAncestor <UserControl>();
                }

                DragAdorner = new DragAdorner(rootElement, adornment);
            }
        }
Exemple #10
0
        /// <summary>
        /// 构造方法
        /// </summary>
        public CSWin()
        {
            var ctemp = new ControlTemplate(typeof(Window));

            {
                var _border = new FrameworkElementFactory(typeof(Border));
                _border.SetValue(Border.BackgroundProperty, Brushes.Transparent);
                _border.SetValue(Border.SnapsToDevicePixelsProperty, true);
                _border.SetBinding(Border.BorderBrushProperty, new Binding()
                {
                    Source = this,
                    Path   = new PropertyPath("CSBorderBrush"),
                    Mode   = BindingMode.TwoWay,
                    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                });
                _border.SetBinding(Border.BorderThicknessProperty, new Binding()
                {
                    Source = this,
                    Path   = new PropertyPath("CSBorderThickness"),
                    Mode   = BindingMode.TwoWay,
                    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                });
                _border.SetBinding(Border.CornerRadiusProperty, new Binding()
                {
                    Source = this,
                    Path   = new PropertyPath("CSCornerRadius"),
                    Mode   = BindingMode.TwoWay,
                    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                });
                {
                    var _workarea = new FrameworkElementFactory(typeof(Grid));
                    _workarea.SetBinding(Grid.MarginProperty, new Binding()
                    {
                        Source = this,
                        Path   = new PropertyPath("CSWorkareaMargin"),
                        Mode   = BindingMode.TwoWay,
                        UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                    });
                    _workarea.SetBinding(Grid.BackgroundProperty, new Binding()
                    {
                        Source = this,
                        Path   = new PropertyPath("Background"),
                        Mode   = BindingMode.TwoWay,
                        UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                    });
                    {
                        var __waRd1 = new FrameworkElementFactory(typeof(RowDefinition));
                        var __waRd2 = new FrameworkElementFactory(typeof(RowDefinition));
                        __waRd1.SetBinding(RowDefinition.HeightProperty, new Binding()
                        {
                            Source = this,
                            Path   = new PropertyPath("TitleHeight"),
                            Mode   = BindingMode.TwoWay,
                            UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                        });
                        __waRd2.SetBinding(RowDefinition.HeightProperty, new Binding()
                        {
                            Source = this,
                            Path   = new PropertyPath("WorkareaHeight"),
                            Mode   = BindingMode.TwoWay,
                            UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                        });
                        _workarea.AppendChild(__waRd1);
                        _workarea.AppendChild(__waRd2);
                    }
                    {
                        var _grid = new FrameworkElementFactory(typeof(Grid));
                        _grid.SetValue(Grid.RowProperty, 0);
                        _grid.AddHandler(Grid.MouseMoveEvent, new MouseEventHandler(TitleBar_MouseMove));
                        _grid.SetBinding(Grid.BackgroundProperty, new Binding()
                        {
                            Source = this,
                            Path   = new PropertyPath("TitleBackground"),
                            Mode   = BindingMode.TwoWay,
                            UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                        });
                        {
                            var _title = new FrameworkElementFactory(typeof(TextBlock));
                            _title.SetBinding(TextBlock.FontSizeProperty, new Binding()
                            {
                                Source = this,
                                Path   = new PropertyPath("TitleFontSize"),
                                Mode   = BindingMode.TwoWay,
                                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                            });
                            _title.SetBinding(TextBlock.HorizontalAlignmentProperty, new Binding()
                            {
                                Source = this,
                                Path   = new PropertyPath("TitleHorizontalAlignment"),
                                Mode   = BindingMode.TwoWay,
                                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                            });
                            _title.SetBinding(TextBlock.TextProperty, new Binding()
                            {
                                Source = this,
                                Path   = new PropertyPath("Title"),
                                Mode   = BindingMode.TwoWay,
                                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                            });

                            var _dp = new FrameworkElementFactory(typeof(DockPanel));
                            _dp.SetValue(DockPanel.HorizontalAlignmentProperty, HorizontalAlignment.Right);
                            _dp.SetValue(DockPanel.DockProperty, Dock.Right);
                            {
                                var btn_max = new FrameworkElementFactory(typeof(CSWinbtn.MinMax));
                                btn_max.SetValue(CSWinbtn.MinMax.PathDataProperty, Geometry.Parse("M0 0 H15 V11 H0 V2 H1 V10 H14 V2 H0 V0"));
                                btn_max.SetBinding(Button.VisibilityProperty, new Binding()
                                {
                                    Source = this,
                                    Path   = new PropertyPath("TitleMaxBtnVisibility"),
                                    Mode   = BindingMode.TwoWay,
                                    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                                });
                                btn_max.SetBinding(Button.WidthProperty, new Binding()
                                {
                                    Source = this,
                                    Path   = new PropertyPath("TitleBtnWidth"),
                                    Mode   = BindingMode.TwoWay,
                                    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                                });
                                btn_max.AddHandler(Button.ClickEvent, handler: new RoutedEventHandler(btn_max_Click));

                                var btn_min = new FrameworkElementFactory(typeof(CSWinbtn.MinMax));
                                btn_min.SetBinding(Button.VisibilityProperty, new Binding()
                                {
                                    Source = this,
                                    Path   = new PropertyPath("TitleMinBtnVisibility"),
                                    Mode   = BindingMode.TwoWay,
                                    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                                });
                                btn_min.SetBinding(Button.WidthProperty, new Binding()
                                {
                                    Source = this,
                                    Path   = new PropertyPath("TitleBtnWidth"),
                                    Mode   = BindingMode.TwoWay,
                                    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                                });
                                btn_min.AddHandler(Button.ClickEvent, handler: new RoutedEventHandler(btn_min_Click));

                                var btn_close = new FrameworkElementFactory(typeof(CSWinbtn.Close));
                                btn_close.SetBinding(Button.VisibilityProperty, new Binding()
                                {
                                    Source = this,
                                    Path   = new PropertyPath("TitleCloseBtnVisibility"),
                                    Mode   = BindingMode.TwoWay,
                                    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                                });
                                btn_close.SetBinding(Button.WidthProperty, new Binding()
                                {
                                    Source = this,
                                    Path   = new PropertyPath("TitleBtnWidth"),
                                    Mode   = BindingMode.TwoWay,
                                    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                                });
                                btn_close.AddHandler(Button.ClickEvent, handler: new RoutedEventHandler(btn_close_Click));

                                _dp.AppendChild(btn_min);
                                _dp.AppendChild(btn_max);
                                _dp.AppendChild(btn_close);
                            }
                            var content = new FrameworkElementFactory(typeof(ContentPresenter));
                            content.SetValue(Grid.RowProperty, 1);

                            _grid.AppendChild(_title);
                            _grid.AppendChild(_dp);

                            _workarea.AppendChild(content);
                        }
                        _workarea.AppendChild(_grid);
                    }
                    _border.AppendChild(_workarea);
                }
                ctemp.VisualTree = _border;
            }
            WindowChrome.SetWindowChrome(this, new WindowChrome()
            {
                ResizeBorderThickness = new Thickness(5),
                CaptionHeight         = 0
            });
            this.Template      = ctemp;
            WindowStyle        = WindowStyle.None;
            AllowsTransparency = true;
            Loaded            += _window_Loaded;
            Deactivated       += CSWin_Deactivated;
            Activated         += CSWin_Activated;
            activatedBrush     = CSBorderBrush;
        }
        void Initialize(bool hasOptionSelector, bool showEditor, List <HUI_Gradient> presets)
        {
            Orientation = Orientation.Vertical;
            MainCanvas  = new Canvas();
            Children.Add(MainCanvas);
            Margin            = new Thickness(10);
            HasOptionSelector = hasOptionSelector;
            GradientHeight    = 40;
            SelectorHeight    = 30;
            MainCanvas.Height = GradientHeight;
            gradientDisplay   = new Rectangle();
            backgroundDisplay = new Rectangle();
            MainCanvas.Children.Add(backgroundDisplay);
            MainCanvas.Children.Add(gradientDisplay);
            if (!showEditor)
            {
                MainCanvas.Visibility = Visibility.Collapsed;
            }
            handles = new List <GradientHandle>();
            handles.Add(new GradientHandle(0, Color.FromRgb(0, 0, 0), this));
            handles.Add(new GradientHandle(1, Color.FromRgb(255, 255, 255), this));
            Binding widthBinding = new Binding()
            {
                Source = this, Path = new PropertyPath("ActualWidth"), Mode = BindingMode.OneWay
            };

            //  Binding heightBinding = new Binding() { Source = this, Path = new PropertyPath("Height"), Mode = BindingMode.OneWay };
            MainCanvas.SetBinding(Canvas.WidthProperty, widthBinding);
            gradientDisplay.SetBinding(WidthProperty, widthBinding);
            gradientDisplay.Height = GradientHeight;
            backgroundDisplay.SetBinding(WidthProperty, widthBinding);
            backgroundDisplay.Height = GradientHeight;
            backgroundDisplay.Fill   = TransparencyGrid();
            gradientDisplay.Stroke   = new SolidColorBrush(Color.FromRgb(0, 0, 0));

            if (presets != null && presets.Count != 0)
            {
                handles = LoadFromGradient(presets[0]);
            }


            if (HasOptionSelector)
            {
                //List<HUI_Gradient> presets = GeneratePresets();

                OptionSelector = new ComboBox();

                FrameworkElementFactory fef = new FrameworkElementFactory(typeof(DockPanel));

                fef.SetValue(Rectangle.WidthProperty, widthBinding);
                fef.SetValue(Rectangle.HeightProperty, (double)20);

                FrameworkElementFactory gradientFEF = new FrameworkElementFactory(typeof(Rectangle));
                gradientFEF.SetValue(Rectangle.FillProperty, new Binding("Brush"));
                FrameworkElementFactory whiteSpaceFEF = new FrameworkElementFactory(typeof(Rectangle));

                whiteSpaceFEF.SetValue(Rectangle.WidthProperty, (double)30);
                whiteSpaceFEF.SetValue(DockPanel.DockProperty, Dock.Right);
                gradientFEF.SetValue(Rectangle.HorizontalAlignmentProperty, HorizontalAlignment.Stretch);
                fef.AppendChild(whiteSpaceFEF);
                fef.AppendChild(gradientFEF);
                DataTemplate itemTemplate = new DataTemplate()
                {
                    VisualTree = fef
                };
                OptionSelector.ItemTemplate  = itemTemplate;
                OptionSelector.SelectedIndex = 0;
                OptionSelector.Height        = SelectorHeight;
                OptionSelector.SetBinding(WidthProperty, widthBinding);
                OptionSelector.ItemsSource       = presets;
                OptionSelector.SelectionChanged += OptionSelector_SelectionChanged;
                Children.Add(OptionSelector);
            }



            KeyDown += HUI_GradientEditor_KeyDown;

            MouseDown += Canvas_MouseDown;
            UpdateGradient();
        }
Exemple #12
0
        public void PolygonButtonSet(string name, Button button, double[] p, bool sh)//Button要素のコントロールテンプレートおよびプロパティ更新メソッド
        {
            //this.header.Content = windowWidth.ToString(format);//小数第二位まで テスト用
            double contentSize = 1;

            if (button != null)
            {//ListBoxのItems(nullを渡している)のフォントサイズはこのメソッドでは指定しない
                contentSize = button.Content.ToString().Replace("\n", "").Length;
            }

            double angle;

            if (name == "MemberButton")
            {
                angle = 5;
            }
            else if (name == "MatchingButton")
            {
                angle = -4;//だいたい文字数の逆比
            }
            else
            {
                angle = 0;
            }

            //Style buttonStyle = new Style(typeof(Button));
            ControlTemplate buttonTemplate = new ControlTemplate(typeof(Button));

            RotateTransform rotateTransform1 = new RotateTransform(angle);

            rotateTransform1.CenterX = (p[0] + (p[0] + p[2])) / 2.0;
            rotateTransform1.CenterY = (p[1] + (p[1] + p[3])) / 2.0;

            FrameworkElementFactory gri = new FrameworkElementFactory(typeof(Grid));

            FrameworkElementFactory  pol = new FrameworkElementFactory(typeof(Polygon));
            TemplateBindingExtension b   = new TemplateBindingExtension(Button.BackgroundProperty);

            pol.SetValue(Polygon.FillProperty, b);//pol要素のFillプロパティをbindingでバインドしますの意
            pol.SetValue(Polygon.PointsProperty, PolygonPoints(p));
            pol.SetValue(Polygon.CursorProperty, Cursors.Hand);
            if (name == "MemberNameButton" || name == "MemberDeleteButton" || name == "ParticipantMemberButton" || name == "ComaAlgorithmButton0" || name == "ComaAlgorithmButton1" || name == "ComaAlgorithmButton2")
            {//ListBoxでボタンを横に配置するため
                pol.SetValue(ContentPresenter.MarginProperty, new Thickness(rowSize * p[0], 0, 0, 0));
            }
            //pol.SetValue(Polygon.NameProperty, "memberPolygon");//何故かこの方法ではNameはセットされない
            if (!sh) /*button == null || name == "GroupAddButton" || name == "GroupDeleteButton"
                     || name == "MemberAddButton" || name=="TableButton" || name == "ComaButton"
                     || name == "ComaAlgorithm0" || name == "ComaAlgorithm1" || name == "ComaAlgorithm2" || name == "ParticipantMemberButton")//!shadowでも可?*/
            {        //ボタンの枠線表示する
                pol.SetValue(Polygon.StrokeProperty, Brushes.Black);
                //pol.SetValue(Polygon.StrokeThicknessProperty, Shape.StrokeThickness(1));
            }

            FrameworkElementFactory con       = new FrameworkElementFactory(typeof(ContentPresenter));
            FrameworkElementFactory conShadow = new FrameworkElementFactory(typeof(ContentPresenter));

            if (button == null)
            {                                                                   //ListBoxItems
                con.SetValue(ContentPresenter.IsHitTestVisibleProperty, false); //テキストにはマウス判定を持たせない
                con.SetValue(ContentPresenter.VerticalAlignmentProperty, VerticalAlignment.Center);
                if (name == "MemberNameButton" || name == "MemberDeleteButton" || name == "ParticipantMemberButton" || name == "ComaAlgorithmButton0" || name == "ComaAlgorithmButton1" || name == "ComaAlgorithmButton2")
                {//ListBoxでボタンを横に配置するため
                    con.SetValue(ContentPresenter.MarginProperty, new Thickness(rowSize * (0.2 + p[0]), 0, 0, 0));
                }
                else if (name == "MemberRankButton")
                {
                    con.SetValue(ContentPresenter.MarginProperty, new Thickness(rowSize * 0.2, 0, 0, 0));
                }
                else
                {
                    con.SetValue(ContentPresenter.MarginProperty, new Thickness(rowSize * 1, 0, 0, 0));
                }
            }
            else if (name == "GroupAddButton" || name == "GroupDeleteButton" || name == "MemberAddButton")
            {                                                                                              //縦書きなので別処理,かつ,影をもたせない
                con.SetValue(ContentPresenter.MarginProperty, PortrateMarginCenter(p, contentSize, name)); //マージンにより左端中央に配置
                con.SetValue(ContentPresenter.RenderTransformProperty, rotateTransform1);
                con.SetValue(ContentPresenter.IsHitTestVisibleProperty, false);                            //テキストにはマウス判定を持たせない
            }
            else if (name == "ToMenuButton" || name == "NextButton")
            {
                //縦書きなので別処理
                con.SetValue(ContentPresenter.MarginProperty, PortrateMarginCenter(p, contentSize, name)); //マージンにより左端中央に配置
                con.SetValue(ContentPresenter.RenderTransformProperty, rotateTransform1);
                con.SetValue(ContentPresenter.IsHitTestVisibleProperty, false);                            //テキストにはマウス判定を持たせない

                conShadow.SetValue(TextBlock.ForegroundProperty, Brushes.Black);
                conShadow.SetValue(ContentPresenter.MarginProperty, PortrateMarginCenterS(p, contentSize)); //マージンにより左端中央に配置
                conShadow.SetValue(ContentPresenter.RenderTransformProperty, rotateTransform1);
                conShadow.SetValue(ContentPresenter.IsHitTestVisibleProperty, false);                       //テキストにはマウス判定を持たせない
            }
            else
            {
                Thickness c;
                Thickness s;
                if (name == "ConfigButton")
                {
                    c = MarginLeftCenter(p, contentSize);
                    s = MarginLeftCenterS(p, contentSize);
                }
                else
                {
                    c = MarginCenter(p, contentSize, name);
                    s = MarginCenterS(p, contentSize, name);
                }
                con.SetValue(ContentPresenter.MarginProperty, c);               //マージンにより左端中央に配置
                con.SetValue(ContentPresenter.RenderTransformProperty, rotateTransform1);
                con.SetValue(ContentPresenter.IsHitTestVisibleProperty, false); //テキストにはマウス判定を持たせない

                conShadow.SetValue(TextBlock.ForegroundProperty, Brushes.Black);
                conShadow.SetValue(ContentPresenter.MarginProperty, s);               //マージンにより左端中央に配置
                conShadow.SetValue(ContentPresenter.RenderTransformProperty, rotateTransform1);
                conShadow.SetValue(ContentPresenter.IsHitTestVisibleProperty, false); //テキストにはマウス判定を持たせない
            }
            if (sh)
            {
                gri.AppendChild(pol);
                gri.AppendChild(conShadow);
                gri.AppendChild(con);
            }
            else
            {
                gri.AppendChild(pol);
                gri.AppendChild(con);
            }

            //pol.Name = "buttonPolygon";//この方法だとNameはセットされる
            buttonTemplate.VisualTree = gri;

            //Setter buttonTemplateSetter = new Setter(TemplateProperty, buttonTemplate);
            //buttonStyle.Setters.Add(buttonTemplateSetter);

            App.Current.Resources[name] = buttonTemplate;//コントロールテンプレート更新

            if (button != null)
            {//ListBoxのItemsに関してはフォントサイズを各自で設定する(全てのItemが同じテンプレートを参照するため)
                //が,MemberButtonsのNameボタンに関してはRankボタンの横に配置するためにマージンを設定する
                button.Margin = new Thickness(rowSize * p[0], columnSize * p[1], 0, 0);
                if (name == "ToMenuButton" || name == "NextButton")                // || name == "GroupAddButton" || name == "GroupDeleteButton" || name == "MemberAddButton")
                {                                                                  //縦書き
                    button.FontSize = columnSize * p[3] * 1.0 / contentSize * 0.3; //フォントサイズ=80% * ボタンの縦幅/文字数
                }
                else if (name == "GroupDeleteButton" || name == "GroupAddButton" || name == "MemberAddButton")
                {                                                                  //縦書き(文字数の関係でボタンによって比率を変えている)
                    button.FontSize = columnSize * p[3] * 1.0 / contentSize * 0.4; //フォントサイズ=80% * ボタンの縦幅/文字数
                }
                else
                {
                    double fontSize = rowSize * p[2] * 1.0 / contentSize * 0.8;
                    if (fontSize > columnSize * p[3] * 0.8)
                    {//縦幅を超えてしまわないように
                        fontSize = columnSize * p[3] * 0.8;
                    }
                    button.FontSize = fontSize;//フォントサイズ=80% * ボタンの横幅/文字数
                }
            }
        }
Exemple #13
0
        private FrameworkElementFactory CreateExpanderDock()
        {
            var dockFactory = new FrameworkElementFactory(typeof(DockPanel));

            var source = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(ExTreeViewItem), 1);

            Style expanderStyle = new Style(typeof(SWC.Primitives.ToggleButton));

            expanderStyle.Setters.Add(new Setter(UIElement.FocusableProperty, false));
            expanderStyle.Setters.Add(new Setter(FrameworkElement.WidthProperty, 19d));
            expanderStyle.Setters.Add(new Setter(FrameworkElement.HeightProperty, 13d));

            var expanderTemplate = new ControlTemplate(typeof(SWC.Primitives.ToggleButton));

            var outerBorderFactory = new FrameworkElementFactory(typeof(Border));

            outerBorderFactory.SetValue(FrameworkElement.WidthProperty, 19d);
            outerBorderFactory.SetValue(FrameworkElement.HeightProperty, 13d);
            outerBorderFactory.SetValue(Control.BackgroundProperty, Brushes.Transparent);
            outerBorderFactory.SetBinding(UIElement.VisibilityProperty,
                                          new Binding("HasItems")
            {
                RelativeSource = source, Converter = BoolVisibilityConverter
            });

            var innerBorderFactory = new FrameworkElementFactory(typeof(Border));

            innerBorderFactory.SetValue(FrameworkElement.WidthProperty, 9d);
            innerBorderFactory.SetValue(FrameworkElement.HeightProperty, 9d);
            innerBorderFactory.SetValue(Control.BorderThicknessProperty, new Thickness(1));
            innerBorderFactory.SetValue(Control.BorderBrushProperty, new SolidColorBrush(Color.FromRgb(120, 152, 181)));
            innerBorderFactory.SetValue(Border.CornerRadiusProperty, new CornerRadius(1));
            innerBorderFactory.SetValue(UIElement.SnapsToDevicePixelsProperty, true);

            innerBorderFactory.SetValue(Control.BackgroundProperty, ExpanderBackgroundBrush);

            var pathFactory = new FrameworkElementFactory(typeof(Path));

            pathFactory.SetValue(FrameworkElement.MarginProperty, new Thickness(1));
            pathFactory.SetValue(Shape.FillProperty, Brushes.Black);
            pathFactory.SetBinding(Path.DataProperty,
                                   new Binding("IsChecked")
            {
                RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(SWC.Primitives.ToggleButton), 1),
                Converter      = BooleanGeometryConverter
            });

            innerBorderFactory.AppendChild(pathFactory);
            outerBorderFactory.AppendChild(innerBorderFactory);

            expanderTemplate.VisualTree = outerBorderFactory;

            expanderStyle.Setters.Add(new Setter(Control.TemplateProperty, expanderTemplate));

            var toggleFactory = new FrameworkElementFactory(typeof(SWC.Primitives.ToggleButton));

            toggleFactory.SetValue(FrameworkElement.StyleProperty, expanderStyle);
            toggleFactory.SetBinding(FrameworkElement.MarginProperty,
                                     new Binding("Level")
            {
                RelativeSource = source, Converter = LevelConverter
            });
            toggleFactory.SetBinding(SWC.Primitives.ToggleButton.IsCheckedProperty,
                                     new Binding("IsExpanded")
            {
                RelativeSource = source
            });
            toggleFactory.SetValue(SWC.Primitives.ButtonBase.ClickModeProperty, ClickMode.Press);

            dockFactory.AppendChild(toggleFactory);
            return(dockFactory);
        }
Exemple #14
0
 void UcTableView_SizeChanged(object sender, SizeChangedEventArgs e)
 {
     if (dt == null)
     {
         return;
     }
     _gridview.Columns.Clear();
     foreach (DataColumn c in dt.Columns)
     {
         GridViewColumn gvc = new GridViewColumn();
         gvc.Header = c.ColumnName;
         if (_listview.ActualWidth > 0)
         {
             if (BShowDetails || BShowModify)
             {
                 gvc.Width = (_listview.ActualWidth - 65) / dt.Columns.Count;
             }
             else
             {
                 gvc.Width = (_listview.ActualWidth - 25) / dt.Columns.Count;
             }
         }
         gvc.SetValue(HorizontalAlignmentProperty, HorizontalAlignment.Center);
         //gvc.DisplayMemberBinding = (new Binding(c.ColumnName));
         FrameworkElementFactory text = new FrameworkElementFactory(typeof(TextBlock));
         text.SetValue(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Center);
         text.SetValue(TextBlock.TextAlignmentProperty, TextAlignment.Center);
         text.SetBinding(TextBlock.TextProperty, new Binding(c.ColumnName));
         DataTemplate dataTemplate = new DataTemplate()
         {
             VisualTree = text
         };
         gvc.CellTemplate = dataTemplate;
         _gridview.Columns.Add(gvc);
     }
     if (BShowDetails)
     {
         GridViewColumn gvc_details = new GridViewColumn();
         gvc_details.Header = "详情";
         FrameworkElementFactory button_details = new FrameworkElementFactory(typeof(Button));
         button_details.SetResourceReference(Button.HorizontalContentAlignmentProperty, HorizontalAlignment.Center);
         button_details.SetValue(Button.WidthProperty, 40.0);
         button_details.AddHandler(Button.ClickEvent, new RoutedEventHandler(details_Click));
         button_details.SetBinding(Button.TagProperty, new Binding(dt.Columns[1].ColumnName));
         button_details.SetValue(Button.ContentProperty, ">>");
         button_details.SetValue(Button.ForegroundProperty, Brushes.White);
         button_details.SetValue(Button.FontSizeProperty, 14.0);
         button_details.SetBinding(Button.VisibilityProperty, new Binding(dt.Columns[0].ColumnName)
         {
             Converter = new VisibleBtnConverter()
         });
         DataTemplate dataTemplate_details = new DataTemplate()
         {
             VisualTree = button_details
         };
         gvc_details.CellTemplate = dataTemplate_details;
         _gridview.Columns.Add(gvc_details);
     }
     if (BShowModify)
     {
         GridViewColumn gvc_modify = new GridViewColumn();
         gvc_modify.Header = "设置";
         FrameworkElementFactory button_modify = new FrameworkElementFactory(typeof(Button));
         button_modify.SetResourceReference(Button.HorizontalContentAlignmentProperty, HorizontalAlignment.Center);
         button_modify.SetValue(Button.WidthProperty, 20.0);
         button_modify.AddHandler(Button.ClickEvent, new RoutedEventHandler(modify_Click));
         button_modify.SetBinding(Button.TagProperty, new Binding(dt.Columns[1].ColumnName));
         button_modify.SetResourceReference(Button.StyleProperty, "ListModifyImageButtonTemplate");
         DataTemplate dataTemplate_modify = new DataTemplate()
         {
             VisualTree = button_modify
         };
         gvc_modify.CellTemplate = dataTemplate_modify;
         _gridview.Columns.Add(gvc_modify);
     }
     _listview.ItemsSource = null;
     _listview.ItemsSource = dt.DefaultView;
 }
Exemple #15
0
        void UpdateColumnDefinitions(IEnumerable <KeyValuePair <string, Type> > columnNamesAndTypes)
        {
            if (m_selectedTable == null)
            {
                RowGrid.Columns.Clear();
                RowData.DataContext = null;
                return;
            }

            IEnumerable <DBRow> indexInfo;

            if (m_selectedIndex != null)
            {
                indexInfo = m_viewModel.GetIndexInfo(m_selectedTable, m_selectedIndex);
            }
            else
            {
                indexInfo = new List <DBRow>(); // empty
            }

            RowGrid.Columns.Clear();

            foreach (KeyValuePair <string, Type> colspec in columnNamesAndTypes)
            {
                var cellBinding = new Binding();
                cellBinding.Converter          = new DBRowValueConverter();
                cellBinding.ConverterParameter = colspec.Key;
                cellBinding.Mode = BindingMode.OneTime;

                FrameworkElementFactory cellFactory;
                if (colspec.Value == typeof(bool?))
                {
                    cellFactory = new FrameworkElementFactory(typeof(CheckBox));
                    cellFactory.SetBinding(CheckBox.IsCheckedProperty, cellBinding);

                    // HACK: Don't allow changes, but don't gray it out either like IsEnabled does.
                    cellFactory.SetValue(CheckBox.IsHitTestVisibleProperty, false);
                    cellFactory.SetValue(CheckBox.FocusableProperty, false);
                }
                else
                {
                    //cellFactory = new FrameworkElementFactory(typeof(ContentControl));
                    //cellFactory.SetBinding(ContentControl.ContentProperty, cellBinding);

                    //cellFactory = new FrameworkElementFactory(typeof(TextBlock));
                    //cellFactory.SetBinding(TextBlock.TextProperty, cellBinding);

                    cellFactory = new FrameworkElementFactory(typeof(TextBox));
                    cellFactory.SetBinding(TextBox.TextProperty, cellBinding);
                    cellFactory.SetValue(TextBox.IsReadOnlyProperty, true);
                    cellFactory.SetValue(TextBox.StyleProperty, FindResource("SelectableTextBlock"));
                }

                var template = new DataTemplate();
                template.VisualTree = cellFactory;

                var gridColumn = new GridViewColumn();
                gridColumn.Header       = colspec.Key;
                gridColumn.CellTemplate = template;

                // Bold the column header if it's part of the current index.
                if (indexInfo.Any(o => o.GetValue("ColumnName").Equals(colspec.Key)))
                {
                    var style = new Style(typeof(GridViewColumnHeader));
                    style.Setters.Add(new Setter(GridViewColumnHeader.FontWeightProperty, FontWeights.Bold));
                    gridColumn.HeaderContainerStyle = style;

                    // Set the column cells to bold as well.
                    cellFactory.SetValue(ContentControl.FontWeightProperty, FontWeights.Bold);
                }

                RowGrid.Columns.Add(gridColumn);
            }
        }
Exemple #16
0
        private DataTemplate Create()
        {
            // create the data template
            var cardLayout = new DataTemplate {
                DataType = typeof(TabItem)
            };

            // set up the stack panel
            var stackPanel = new FrameworkElementFactory(typeof(StackPanel))
            {
                Name = "myComboFactory"
            };

            // set up the border
            var mainBorder = new FrameworkElementFactory(typeof(Border))
            {
                Name = "Border"
            };

            mainBorder.SetValue(HeightProperty, 40.0);
            mainBorder.SetValue(WidthProperty, 40.0);
            mainBorder.SetValue(MarginProperty, new Thickness(10, 5, 10, 12)); // 10, 5, 17, 12
            mainBorder.SetValue(Border.BorderBrushProperty, Brushes.Black);
            mainBorder.SetValue(Border.BorderThicknessProperty, new Thickness(1));
            mainBorder.SetValue(Border.CornerRadiusProperty, new CornerRadius(20));

            // set up the number Textblock
            var textBlockInsideBorder = new FrameworkElementFactory(typeof(TextBlock))
            {
                Name = "TextBlock"
            };

            textBlockInsideBorder.SetValue(TextBlock.FontWeightProperty, FontWeights.ExtraBold);
            textBlockInsideBorder.SetValue(TextBlock.ForegroundProperty, Brushes.White);
            textBlockInsideBorder.SetValue(VerticalAlignmentProperty, VerticalAlignment.Center);
            textBlockInsideBorder.SetValue(HorizontalAlignmentProperty, HorizontalAlignment.Center);
            textBlockInsideBorder.SetBinding(TextBlock.TextProperty, new Binding("ItemNumber"));

            // add text block inside border
            mainBorder.AppendChild(textBlockInsideBorder);

            stackPanel.AppendChild(mainBorder);

            // set up the number Textblock
            var headerTextBlock = new FrameworkElementFactory(typeof(TextBlock))
            {
                Name = "HeaderTextBlock"
            };

            headerTextBlock.SetValue(TextBlock.ForegroundProperty, Brushes.DarkGray);
            headerTextBlock.SetValue(VerticalAlignmentProperty, VerticalAlignment.Center);
            headerTextBlock.SetValue(HorizontalAlignmentProperty, HorizontalAlignment.Center);
            headerTextBlock.SetBinding(TextBlock.TextProperty, new Binding("ItemHeader"));

            stackPanel.AppendChild(headerTextBlock);

            // set the visual tree of the data template
            cardLayout.VisualTree = stackPanel;

            // visited events and setters.
            var visitedSetter = new Setter
            {
                TargetName = "Border",
                Property   = Border.BackgroundProperty,
                Value      = Brushes.Gray
            };

            var visitedTrigger = new Trigger {
                Property = IsEnabledProperty, Value = false
            };

            visitedTrigger.Setters.Add(visitedSetter);

            var setter = new Setter
            {
                TargetName = "Border",
                Property   = Border.BackgroundProperty,
                Value      = Brushes.DarkGray
            };

            var trigger = new Trigger {
                Property = IsEnabledProperty, Value = false
            };

            trigger.Setters.Add(setter);

            var isEnablesSetter2 = new Setter
            {
                TargetName = "Border",
                Property   = Border.BackgroundProperty,
                Value      = Brushes.CornflowerBlue
            };

            var isEnablesSetter3 = new Setter
            {
                TargetName = "HeaderTextBlock",
                Property   = TextBlock.FontWeightProperty,
                Value      = FontWeights.ExtraBold
            };

            var trigger2 = new Trigger {
                Property = IsEnabledProperty, Value = true
            };

            trigger2.Setters.Add(isEnablesSetter2);
            trigger2.Setters.Add(isEnablesSetter3);

            cardLayout.Triggers.Add(trigger);
            cardLayout.Triggers.Add(trigger2);

            return(cardLayout);
        }
Exemple #17
0
        public override void Load(NetworkLogViewerBase viewer)
        {
            if (m_viewer != null)
            {
                throw new InvalidOperationException();
            }

            // Check opcode integrity
            {
                Console.WriteLine("Debug: Protocol '{0}' build {1} checking opcode integrity...",
                                  this.CodeName, Disassembly.ClientBuild);
                var fields = typeof(WowOpcodes).GetFields(BindingFlags.Static | BindingFlags.Public);

                var list = new SortedSet <uint>();
                foreach (var field in fields)
                {
                    var value = (uint)field.GetRawConstantValue();
                    if (value != SpecialOpcodes.UnknownOpcode)
                    {
                        if (!list.Contains(value))
                        {
                            list.Add(value);
                        }
                        else
                        {
                            Console.WriteLine("Error: Protocol '{1}' duplicate opcode value {0}",
                                              value, this.CodeName);
                        }
                    }
                }
                Console.WriteLine(
                    "Debug: Integrity check complete, {0}/{1} ({2:0.00}%) known unique opcode values.",
                    list.Count,
                    fields.Length,
                    list.Count * 100.0 / fields.Length
                    );
            }

            m_viewer = viewer;
            viewer.ItemVisualDataQueried += m_itemVisualDataQueriedHandler;
            viewer.ItemParsingDone       += m_itemParsingDoneHandler;

            var view = m_view = new GridView();

            var nColumns = s_columnWidths.Length;
            var headers  = new string[]
            {
                NetworkStrings.CH_Number,
                NetworkStrings.CH_Time,
                NetworkStrings.CH_Ticks,
                Strings.CH_ConnId,
                NetworkStrings.CH_C2S,
                NetworkStrings.CH_S2C,
                NetworkStrings.CH_Length,
                Strings.CH_Preview,
            };

            if (headers.Length != nColumns)
            {
                throw new InvalidOperationException();
            }

            double[] widths = Configuration.GetValue("Column Widths", (double[])null);
            if (widths == null || widths.Length != nColumns)
            {
                widths = s_columnWidths;
            }

            int[] columnOrder = Configuration.GetValue("Column Order", (int[])null);
            if (columnOrder == null || columnOrder.Length != nColumns ||
                columnOrder.Any(val => val >= nColumns || val < 0))
            {
                columnOrder = Enumerable.Range(0, nColumns).ToArray();
            }

            if (s_customBrush == null)
            {
                s_customBrush = new SolidColorBrush(Color.FromRgb(132, 22, 35));
            }

            if (s_freezedBrush == null)
            {
                s_freezedBrush = new SolidColorBrush(Color.FromRgb(36, 176, 185));
            }

            for (int i = 0; i < nColumns; i++)
            {
                int col = columnOrder[i];

                var item = new GridViewColumnWithId();
                item.ColumnId = col;
                item.Header   = headers[col];
                item.Width    = widths[col];

                var dataTemplate = new DataTemplate();
                dataTemplate.DataType = typeof(ItemVisualData);

                var block = new FrameworkElementFactory(typeof(TextBlock));
                block.Name = "tb";
                block.SetValue(TextBlock.TextProperty, new Binding(s_columnBindings[col]));

                // Opcode
                if (col == 4 || col == 5)
                {
                    block.SetValue(TextBlock.FontFamilyProperty, new FontFamily("Lucida Console"));

                    DataTrigger trigger;

                    trigger         = new DataTrigger();
                    trigger.Binding = new Binding(".VisualData.IsCustom");
                    trigger.Value   = true;
                    trigger.Setters.Add(new Setter(TextBlock.ForegroundProperty, s_customBrush, "tb"));
                    dataTemplate.Triggers.Add(trigger);

                    trigger         = new DataTrigger();
                    trigger.Binding = new Binding(".VisualData.IsFreezed");
                    trigger.Value   = true;
                    trigger.Setters.Add(new Setter(TextBlock.ForegroundProperty, s_freezedBrush, "tb"));
                    dataTemplate.Triggers.Add(trigger);

                    trigger         = new DataTrigger();
                    trigger.Binding = new Binding(".VisualData.IsUndefinedParser");
                    trigger.Value   = true;
                    trigger.Setters.Add(new Setter(TextBlock.ForegroundProperty, Brushes.Gray, "tb"));
                    dataTemplate.Triggers.Add(trigger);
                }
                // Preview
                else if (col == 7)
                {
                    var trigger = new DataTrigger();
                    trigger.Binding = new Binding(".VisualData.ParsingError");
                    trigger.Value   = true;
                    trigger.Setters.Add(new Setter(TextBlock.ForegroundProperty, Brushes.Red, "tb"));
                    dataTemplate.Triggers.Add(trigger);
                }

                dataTemplate.VisualTree = block;
                item.CellTemplate       = dataTemplate;

                view.Columns.Add(item);
            }
        }
Exemple #18
0
        public GridView MakeView()
        {
            GridView gridView = new GridView();

            gridView.Columns.Add(new GridViewColumn()
            {
                Header = "Ид", DisplayMemberBinding = new Binding()
                {
                    Path = new PropertyPath("Id")
                }
            });
            gridView.Columns.Add(new GridViewColumn()
            {
                Header = "Материнская плата", DisplayMemberBinding = new Binding()
                {
                    Path = new PropertyPath("Board.Motherboard")
                }
            });
            gridView.Columns.Add(new GridViewColumn()
            {
                Header = "ЦП", DisplayMemberBinding = new Binding()
                {
                    Path = new PropertyPath("Cpu.NameCPU")
                }
            });
            gridView.Columns.Add(new GridViewColumn()
            {
                Header = "Частота ядра", DisplayMemberBinding = new Binding()
                {
                    Path = new PropertyPath("CpuClockSpeed")
                }
            });
            gridView.Columns.Add(new GridViewColumn()
            {
                Header = "Жесткий диск", DisplayMemberBinding = new Binding()
                {
                    Path = new PropertyPath("Hdd.NameHDD")
                }
            });
            gridView.Columns.Add(new GridViewColumn()
            {
                Header = "Объем", DisplayMemberBinding = new Binding()
                {
                    Path = new PropertyPath("HddCapacity")
                }
            });
            gridView.Columns.Add(new GridViewColumn()
            {
                Header = "ОЗУ", DisplayMemberBinding = new Binding()
                {
                    Path = new PropertyPath("RamCapacity")
                }
            });
            gridView.Columns.Add(new GridViewColumn()
            {
                Header = "Операционная система", DisplayMemberBinding = new Binding()
                {
                    Path = new PropertyPath("OS.NameOS")
                }
            });
            gridView.Columns.Add(new GridViewColumn()
            {
                Header = "Год учёта", DisplayMemberBinding = new Binding()
                {
                    Path = new PropertyPath("YearUsingSince")
                }
            });
            gridView.Columns.Add(new GridViewColumn()
            {
                Header = "Инвентарный №", DisplayMemberBinding = new Binding()
                {
                    Path = new PropertyPath("InventoryNo")
                }
            });
            gridView.Columns.Add(new GridViewColumn()
            {
                Header = "Имя в сети", DisplayMemberBinding = new Binding()
                {
                    Path = new PropertyPath("Hostname")
                }
            });
            gridView.Columns.Add(new GridViewColumn()
            {
                Header = "IP адрес", DisplayMemberBinding = new Binding()
                {
                    Path = new PropertyPath("IpAddress")
                }
            });
            gridView.Columns.Add(new GridViewColumn()
            {
                Header = "Сотрудник", DisplayMemberBinding = new Binding()
                {
                    Path = new PropertyPath("WorkerName")
                }
            });
            gridView.Columns.Add(new GridViewColumn()
            {
                Header = "Кабинет", DisplayMemberBinding = new Binding()
                {
                    Path = new PropertyPath("Room")
                }
            });
            gridView.Columns.Add(new GridViewColumn()
            {
                Header = "Лицензия", DisplayMemberBinding = new Binding()
                {
                    Path = new PropertyPath("License.LicenseState")
                }
            });
            gridView.Columns.Add(new GridViewColumn()
            {
                Header = "Примечание", DisplayMemberBinding = new Binding()
                {
                    Path = new PropertyPath("Note")
                }
            });

            DataTemplate            inUseTemplate = new DataTemplate();
            FrameworkElementFactory inUseFactory  = new FrameworkElementFactory(typeof(CheckBox));

            inUseFactory.SetValue(CheckBox.IsEnabledProperty, false);
            inUseFactory.SetBinding(CheckBox.IsCheckedProperty, new Binding()
            {
                Path = new PropertyPath("InUse")
            });
            inUseTemplate.VisualTree = inUseFactory;
            gridView.Columns.Add(new GridViewColumn()
            {
                Header = "Используется", CellTemplate = inUseTemplate
            });



            return(gridView);
        }
Exemple #19
0
        private DataTemplate makeDataTemplate()
        {
            FrameworkElementFactory textBlockName = new FrameworkElementFactory(typeof(TextBlock));

            //textBlockName.SetValue(TextBlock.NameProperty, "SubjectName");
            textBlockName.SetValue(TextBlock.TextWrappingProperty, TextWrapping.Wrap);
            textBlockName.SetValue(LayoutTransformProperty, new RotateTransform(270));
            //textBlockName.SetValue(WidthProperty, HEIGHT_OF_ROWS_IN_MAIN_GRID);
            //textBlockName.SetBinding(TextBlock.TextProperty, new Binding("Id") {TargetNullValue = "***" });
            textBlockName.SetBinding(TextBlock.TextProperty, new Binding("Subject.Code"));
            textBlockName.SetBinding(TextBlock.ToolTipProperty, new Binding("Subject.Code"));

            FrameworkElementFactory textBlock1 = new FrameworkElementFactory(typeof(TextBlock));

            textBlock1.SetValue(TextBlock.TextProperty, " ");
            textBlock1.SetValue(LayoutTransformProperty, new RotateTransform(270));

            FrameworkElementFactory textBlockMark = new FrameworkElementFactory(typeof(TextBlock));

            //textBlockName.SetValue(TextBlock.NameProperty, "SubjectMark");
            textBlockMark.SetValue(TextBlock.TextWrappingProperty, TextWrapping.Wrap);
            textBlockMark.SetValue(LayoutTransformProperty, new RotateTransform(270));
            //textBlockMark.SetValue(WidthProperty, HEIGHT_OF_ROWS_IN_MAIN_GRID);
            //textBlockMark.SetBinding(TextBlock.TextProperty, new Binding("Id") { TargetNullValue = "***"});
            textBlockMark.SetBinding(TextBlock.TextProperty, new Binding("Subject.Course.Code"));
            textBlockMark.SetBinding(TextBlock.ToolTipProperty, new Binding("Subject.Course.Code"));

            //FrameworkElementFactory textBlock2 = new FrameworkElementFactory(typeof(TextBlock));
            //textBlock2.SetValue(TextBlock.TextProperty, ")");
            //textBlock2.SetValue(LayoutTransformProperty, new RotateTransform(270));

            FrameworkElementFactory stackPanel = new FrameworkElementFactory(typeof(StackPanel));

            stackPanel.SetValue(StackPanel.OrientationProperty, Orientation.Vertical);
            //stackPanel.SetBinding(StackPanel.HeightProperty, new Binding("RowSpan"));
            //stackPanel.SetValue(StackPanel.BackgroundProperty, Brushes.Aqua);
            //wrapPanel.SetValue(WrapPanel.HeightProperty, new GridLength(HEIGHT_OF_ROWS_IN_MAIN_GRID));
            stackPanel.AppendChild(textBlockName);
            stackPanel.AppendChild(textBlock1);
            stackPanel.AppendChild(textBlockMark);
            //stackPanel.AppendChild(textBlock2);

            DataTemplate dataTemplate = null;

            try
            {
                dataTemplate            = new DataTemplate();
                dataTemplate.VisualTree = stackPanel;
            }
            catch { }

            /*DataTrigger dataTriggerName = new DataTrigger();
             * dataTriggerName.Binding = new Binding("Subject.Name");
             * dataTriggerName.Value = null;
             * dataTriggerName.Setters.Add(new Setter(TextBlock.TextProperty, "***"));
             *
             * DataTrigger dataTriggerMark = new DataTrigger();
             * dataTriggerMark.Binding = new Binding("Subject.Mark");
             * dataTriggerMark.Value = null;
             * dataTriggerMark.Setters.Add(new Setter(TextBlock.TextProperty, "***"));
             *
             * dataTemplate.Triggers.Add(dataTriggerName);
             * dataTemplate.Triggers.Add(dataTriggerMark);*/

            return(dataTemplate);
        }
Exemple #20
0
        public void EllipseButtonSet(string name, Button button, double[] p, bool sh)//Button要素のコントロールテンプレートおよびプロパティ更新メソッド
        {
            //this.header.Content = windowWidth.ToString(format);//小数第二位まで テスト用
            double contentSize = 1;

            contentSize = button.Content.ToString().Replace("\n", "").Length;

            ControlTemplate buttonTemplate = new ControlTemplate(typeof(Button));

            FrameworkElementFactory gri = new FrameworkElementFactory(typeof(Grid));

            FrameworkElementFactory  el = new FrameworkElementFactory(typeof(Ellipse));
            TemplateBindingExtension b  = new TemplateBindingExtension(Button.BackgroundProperty);

            el.SetValue(Ellipse.FillProperty, b); //pol要素のFillプロパティをbindingでバインドしますの意
            if (name == "GroupNameChangeButton" || name == "GroupOpenButton")
            {                                     //真円
                el.SetValue(Ellipse.StrokeProperty, Brushes.Black);
                if (rowSize > columnSize)
                {
                    el.SetValue(Ellipse.WidthProperty, columnSize * p[2]);
                    el.SetValue(Ellipse.HeightProperty, columnSize * p[3]);
                }
                else
                {
                    el.SetValue(Ellipse.WidthProperty, rowSize * p[2]);
                    el.SetValue(Ellipse.HeightProperty, rowSize * p[3]);
                }
            }
            else
            {
                el.SetValue(Ellipse.WidthProperty, rowSize * p[2]);
                el.SetValue(Ellipse.HeightProperty, columnSize * p[3]);
            }
            el.SetValue(Ellipse.HorizontalAlignmentProperty, HorizontalAlignment.Left);
            el.SetValue(Ellipse.VerticalAlignmentProperty, VerticalAlignment.Top);
            el.SetValue(Ellipse.CursorProperty, Cursors.Hand);
            //pol.SetValue(Polygon.NameProperty, "memberPolygon");//何故かセットされない

            FrameworkElementFactory con       = new FrameworkElementFactory(typeof(ContentPresenter));
            FrameworkElementFactory conShadow = new FrameworkElementFactory(typeof(ContentPresenter));

            con.SetValue(ContentPresenter.IsHitTestVisibleProperty, false);//テキストにはマウス判定を持たせない
            if (name == "GroupNameChangeButton" || name == "GroupOpenButton")
            {
                con.SetValue(ContentPresenter.MarginProperty, CircleMarginCenter(p, contentSize, name));
            }
            else
            {
                con.SetValue(ContentPresenter.MarginProperty, MarginCenter(p, contentSize, name));
            }

            if (sh)
            {
                gri.AppendChild(el);
                gri.AppendChild(con);
            }
            else
            {
                gri.AppendChild(el);
                gri.AppendChild(con);
            }


            //pol.Name = "buttonPolygon";//この方法だとセットされる
            buttonTemplate.VisualTree = gri;

            App.Current.Resources[name] = buttonTemplate;//コントロールテンプレート更新
            button.Margin = new Thickness(rowSize * p[0], columnSize * p[1], 0, 0);
            if (name == "GroupNameChangeButton" || name == "GroupOpenButton")
            {
                if (rowSize > columnSize)
                {
                    button.FontSize = columnSize * p[2] * 1.0 / contentSize * 0.8;//フォントサイズ=80% * ボタンの縦幅/文字数
                }
                else
                {
                    button.FontSize = rowSize * p[2] * 1.0 / contentSize * 0.8;//フォントサイズ=80% * ボタンの横幅/文字数
                }
            }
            else
            {
                button.FontSize = rowSize * p[2] * 1.0 / contentSize * 0.8;//フォントサイズ=80% * ボタンの横幅/文字数
            }
        }
Exemple #21
0
        public static bool ConceptDefinitionEdit(Domain SourceDomain, IList <ConceptDefinition> EditedList, ConceptDefinition ConceptDef)
        {
            /*- if (!ProductDirector.ConfirmImmediateApply("Concept Definition", "DomainEdit.ConceptDefinition", "ApplyDialogChangesDirectly"))
             *  return false; */

            var CurrentWindow = Display.GetCurrentWindow();

            CurrentWindow.Cursor = Cursors.Wait;

            var InstanceController = EntityInstanceController.AssignInstanceController(ConceptDef,
                                                                                       (current, previous, editpanels) =>
            {
                var CurrentDetailsEditor = (GlobalDetailsDefinitor)editpanels.First(editpanel => editpanel is GlobalDetailsDefinitor);
                return(CurrentDetailsEditor.UpdateRelatedDetailDefinitions(ConceptDef));
            });

            var DetDefEd = GlobalDetailsDefinitor.CreateGlobalDetailsDefinitor(InstanceController.EntityEditor, ConceptDef);

            InstanceController.StartEdit();

            var VisualSymbolFormatter = new VisualSymbolFormatSubform("DefaultSymbolFormat");

            var TemplateEd = new TemplateEditor();

            TemplateEd.Initialize(SourceDomain, SourceDomain.CurrentExternalLanguage.TechName, typeof(Concept), ConceptDef,
                                  IdeaDefinition.__OutputTemplates, Domain.__OutputTemplatesForConcepts, false,
                                  Tuple.Create <string, ImageSource, string, Action <string> >("Insert predefined...", Display.GetAppImage("page_white_wrench.png"), "Inserts a system predefined Output-Template text, at the current selection.",
                                                                                               text => { var tpl = DomainServices.GetPredefinedOutputTemplate(); if (tpl != null)
                                                                                                         {
                                                                                                             TemplateEd.SteSyntaxEditor.ReplaceTextAtSelection(tpl);
                                                                                                         }
                                                                                               }),
                                  Tuple.Create <string, ImageSource, string, Action <string> >("Test", Display.GetAppImage("page_white_wrench.png"), "Test the Template against a source Concept.",
                                                                                               text => RememberedTemplateTestConcept[SourceDomain.OwnerComposition] =
                                                                                                   TemplateTester.TestTemplate(typeof(Concept), ConceptDef, IdeaDefinition.__OutputTemplates.Name,
                                                                                                                               ConceptDef.GetGenerationFinalTemplate(TemplateEd.CurrentTemplate.Language, text, TemplateEd.ChbExtendsBaseTemplate.IsChecked.IsTrue()),
                                                                                                                               SourceDomain.OwnerComposition,
                                                                                                                               RememberedTemplateTestConcept.GetValueOrDefault(SourceDomain.OwnerComposition)
                                                                                                                               .NullDefault(SourceDomain.OwnerComposition.CompositeIdeas.OrderBy(idea => idea.Name)
                                                                                                                                            .FirstOrDefault(idea => idea.IdeaDefinitor == ConceptDef)
                                                                                                                                            .NullDefault(SourceDomain.OwnerComposition.DeclaredIdeas
                                                                                                                                                         .FirstOrDefault(idea => idea is Concept))))));

            var TemplateTab = TabbedEditPanel.CreateTab(DomainServices.TABKEY_DEF_OUTTEMPLATE, "Output-Templates", "Definitions of Output-Templates", TemplateEd);

            var SpecTabs = General.CreateList(
                TabbedEditPanel.CreateTab(DomainServices.TABKEY_DEF_ARRANGE, "Arrange", "Settings for relate and group ideas.",
                                          new ArrangeTabForConceptDef(ConceptDef)),
                TabbedEditPanel.CreateTab(DomainServices.TABKEY_DEF_FORMAT, "Symbol format", "Definition for the Symbol format.",
                                          VisualSymbolFormatter),
                TabbedEditPanel.CreateTab(DomainServices.TABKEY_DEF_DETAILS, "Details", "Details definition.", DetDefEd),
                TemplateTab);

            var ExtraGeneralContentsPanel = new Grid();

            ExtraGeneralContentsPanel.ColumnDefinitions.Add(new ColumnDefinition());
            ExtraGeneralContentsPanel.ColumnDefinitions.Add(new ColumnDefinition());

            var ExtraGenContentPanelLeft = new StackPanel();

            Grid.SetColumn(ExtraGenContentPanelLeft, 0);
            ExtraGeneralContentsPanel.Children.Add(ExtraGenContentPanelLeft);

            var ExtraGenContentPanelRight = new StackPanel();

            Grid.SetColumn(ExtraGenContentPanelRight, 1);
            ExtraGeneralContentsPanel.Children.Add(ExtraGenContentPanelRight);

            ExtraGenContentPanelLeft       = new StackPanel();
            ExtraGenContentPanelLeft.Width = 316;
            ExtraGeneralContentsPanel.Children.Add(ExtraGenContentPanelLeft);

            var Expositor = new EntityPropertyExpositor(ConceptDefinition.__IsComposable.TechName);

            Expositor.LabelMinWidth = 130;
            ExtraGenContentPanelLeft.Children.Add(Expositor);

            Expositor = new EntityPropertyExpositor(ConceptDefinition.__IsVersionable.TechName);
            Expositor.LabelMinWidth = 130;
            ExtraGenContentPanelLeft.Children.Add(Expositor);

            Expositor = new EntityPropertyExpositor(ConceptDefinition.__RepresentativeShape.TechName);
            Expositor.LabelMinWidth = 130;
            ExtraGenContentPanelLeft.Children.Add(Expositor);
            Expositor.PostCall(expo =>
            {
                var Combo = expo.ValueEditor as ComboBox;
                if (Combo != null)
                {
                    var Panel = new FrameworkElementFactory(typeof(WrapPanel));
                    Panel.SetValue(WrapPanel.WidthProperty, 810.0);
                    Panel.SetValue(WrapPanel.ItemWidthProperty, 200.0);
                    // Don't work as expected: Panel.SetValue(WrapPanel.OrientationProperty, Orientation.Vertical);
                    var Templ        = new ItemsPanelTemplate(Panel);
                    Combo.ItemsPanel = Templ;
                }
            }, true);

            Expositor = new EntityPropertyExpositor(ConceptDefinition.__PreciseConnectByDefault.TechName);
            Expositor.LabelMinWidth = 130;
            ExtraGenContentPanelLeft.Children.Add(Expositor);

            var ClosuredExpositor = new EntityPropertyExpositor(IdeaDefinition.__Cluster.TechName);

            ClosuredExpositor.LabelMinWidth = 130;
            ExtraGenContentPanelRight.Children.Add(ClosuredExpositor);
            var PropCtl = InstanceController.GetPropertyController(IdeaDefinition.__Cluster.TechName);

            PropCtl.ComplexOptionsProviders =
                Tuple.Create <IRecognizableElement, Action <object> >(
                    new SimplePresentationElement("Edit Clusters", "EditClusters", "Edit Clusters", Display.GetAppImage("def_clusters.png")),
                    obj =>
            {
                if (DomainServices.DefineDomainIdeaDefClusters(SourceDomain, DomainServices.TABKEY_IDEF_CLUSTER_CONCEPT))
                {
                    ClosuredExpositor.RetrieveAvailableItems();
                }
            }).IntoArray();

            var EditPanel = Display.CreateEditPanel(ConceptDef, SpecTabs, true, null, Display.TABKEY_TECHSPEC + General.STR_SEPARATOR + DomainServices.TABKEY_DEF_OUTTEMPLATE,
                                                    true, false, true, true, ExtraGeneralContentsPanel);

            EditPanel.Loaded +=
                ((sender, args) =>
            {
                var OwnerWindow = EditPanel.GetNearestVisualDominantOfType <Window>();
                OwnerWindow.MinWidth = 770;
                OwnerWindow.MinHeight = 550;
                OwnerWindow.PostCall(wnd => CurrentWindow.Cursor = Cursors.Arrow);
            });

            if (IdeaDefinition.__OutputTemplates.IsAdvanced)
            {
                EditPanel.ShowAdvancedMembersChanged +=
                    ((show) =>
                {
                    TemplateTab.SetVisible(show);
                    if (!show)
                    {
                        var OwnerTabControl = TemplateTab.GetNearestDominantOfType <TabControl>();
                        if (OwnerTabControl.SelectedItem == TemplateTab)
                        {
                            OwnerTabControl.SelectedIndex = 0;
                        }
                    }
                });
            }

            var Previewer = new VisualElementPreviewer(VisualSymbolFormatter.VisualElementFormatter.ExpoLineBrush,
                                                       VisualSymbolFormatter.VisualElementFormatter.ExpoLineThickness,
                                                       VisualSymbolFormatter.VisualElementFormatter.ExpoLineDash,
                                                       VisualSymbolFormatter.VisualElementFormatter.ExpoMainBackground);

            Previewer.AttachSource(ConceptDef);
            Previewer.Margin        = new Thickness(4);
            EditPanel.HeaderContent = Previewer;

            var Result = InstanceController.Edit(EditPanel, "Edit Concept Definition - " + ConceptDef.ToString(), true, null,
                                                 CONDEFWND_INI_WIDTH, CONDEFWND_INI_HEIGHT).IsTrue();

            return(Result);
        }
Exemple #22
0
        public void LabelSet(string name, Label label, double[] p, bool sh) //header要素のコントロールテンプレートおよびプロパティ更新メソッド
        {                                                                   //文字を持っていたり多角形であったりするラベルのコントロールテンプレートを設定する
            //テンプレートの再利用を考えるとポリゴンのポジションは原点を左上に指定し,テンプレート外からマージンにより全体の原点座標を設定する(テンプレート内で座標を設定するとそのテンプレートを利用する全コントロールが同じ位置になってしまう)
            //this.header.Content = windowWidth.ToString(format);//小数第二位まで テスト用
            double contentSize = 1;

            if (label != null)
            {//一部のListBoxのItems(nullを渡している)のフォントサイズはこのメソッドでは指定しない(形状は同じだが文字数が異なるため)
                contentSize = label.Content.ToString().Replace("\n", "").Length;
            }

            ControlTemplate labelTemplate = new ControlTemplate(typeof(Label));

            FrameworkElementFactory gri       = new FrameworkElementFactory(typeof(Grid));
            FrameworkElementFactory pol       = new FrameworkElementFactory(typeof(Polygon)); //ポリゴン用
            FrameworkElementFactory cir       = new FrameworkElementFactory(typeof(Ellipse)); //円用
            FrameworkElementFactory con       = new FrameworkElementFactory(typeof(ContentPresenter));
            FrameworkElementFactory conShadow = new FrameworkElementFactory(typeof(ContentPresenter));

            if (true)//name == "Header" || name == "RankNameLabel" || name == "MemberGroupLabel")//多角形ラベル
            {
                pol = new FrameworkElementFactory(typeof(Polygon));
                TemplateBindingExtension b = new TemplateBindingExtension(Label.BackgroundProperty);
                pol.SetValue(Polygon.FillProperty, b);
                pol.SetValue(Polygon.PointsProperty, PolygonPoints(p));
                if (name == "ParticipantRankLabel")
                {
                    pol.SetValue(Polygon.StrokeProperty, new SolidColorBrush(Color.FromRgb(0, 0, 0)));
                    pol.SetValue(Polygon.PointsProperty, PentaPoints(p));
                }
            }
            else//円形ラベル//現状なし
            {
                cir = new FrameworkElementFactory(typeof(Ellipse));
                TemplateBindingExtension b = new TemplateBindingExtension(Label.BackgroundProperty);
                cir.SetValue(Ellipse.FillProperty, b);
                cir.SetValue(Ellipse.WidthProperty, rowSize * p[2]);
                cir.SetValue(Ellipse.HeightProperty, columnSize * p[3]);
            }

            if (name != "MemberGroupLabel")//name == "Header" || name == "RankNameLabel" || name == "ComaAlgorithmLabel")//文字(コンテンツ)を持つラベル
            {
                con = new FrameworkElementFactory(typeof(ContentPresenter));
                if (name == "ParticipantRankLabel")
                {
                    con.SetValue(ContentPresenter.MarginProperty, MarginCenter(p, 1.1, name));//マージンにより左端中央に配置
                }
                else
                {
                    con.SetValue(ContentPresenter.MarginProperty, MarginLeftCenter(p, contentSize));//マージンにより左端中央に配置
                }

                if (label == null)
                {
                    if (name == "ComaAlgorithmLabel")
                    {                                                                 //ComaAlgorithmLabelのとき
                        con.SetValue(TextBlock.FontSizeProperty, rowSize * p[2] / 4); //[i][コ][マ][目]
                    }
                    else
                    {                                                                   //ParticipantRankLabelのとき
                        con.SetValue(TextBlock.FontSizeProperty, rowSize * p[2] / 1.1); //だいたい1桁
                    }
                }
                else if (name == "AlgorithmLabel" || name == "AlgorithmLabel0" || name == "AlgorithmLabel1" || name == "AlgorithmLabel2")
                {
                    double fontSize = rowSize * p[2] / contentSize * 0.8;
                    if (fontSize > columnSize * p[3])
                    {
                        fontSize = columnSize * p[3];
                    }
                    con.SetValue(TextBlock.FontSizeProperty, fontSize);
                }
                else
                {
                    con.SetValue(TextBlock.FontSizeProperty, columnSize * p[3] * 0.7);//フォントサイズ=ヘッダの縦幅の70%
                }

                conShadow = new FrameworkElementFactory(typeof(ContentPresenter));
                conShadow.SetValue(TextBlock.ForegroundProperty, Brushes.Black);
                conShadow.SetValue(TextBlock.FontSizeProperty, columnSize * p[3] * 0.7);

                conShadow.SetValue(ContentPresenter.MarginProperty, MarginLeftCenterS(p, contentSize));//マージンにより左端中央に配置
            }
            else if (name == "MemberGroupLabel")
            {                                                       //縦書き
                con = new FrameworkElementFactory(typeof(ContentPresenter));
                double fontSize = rowSize * p[2] * 0.7;             //フォントサイズ=横幅の70%
                if (fontSize * contentSize > columnSize * p[3])     //フォントサイズが縦幅を超えたとき
                {
                    fontSize = columnSize * p[3] / contentSize;     //フォントサイズ=縦幅/文字数の70%
                }
                con.SetValue(TextBlock.FontSizeProperty, fontSize); //フォントサイズ=横幅の70%
                con.SetValue(ContentPresenter.HorizontalAlignmentProperty, HorizontalAlignment.Left);
                con.SetValue(ContentPresenter.VerticalAlignmentProperty, VerticalAlignment.Top);
            }

            //Grid構築
            if (sh)//name == "Header")
            {
                gri.AppendChild(pol);
                gri.AppendChild(conShadow);
                gri.AppendChild(con);
            }
            else if (!sh)//name == "RankNameLabel" || name == "MemberGroupLabel")
            {
                gri.AppendChild(pol);
                gri.AppendChild(con);
            }
            else if (false)
            {
                gri.AppendChild(cir);
            }

            //ビジュアルツリーに登録
            labelTemplate.VisualTree = gri;

            //コントロールテンプレート更新
            App.Current.Resources[name] = labelTemplate;

            if (label != null)
            {
                label.IsHitTestVisible = false;                                                                                                                                //マウス判定を消す
                label.Margin           = new Thickness(rowSize * p[0], columnSize * p[1], -windowWidth + rowSize * (p[0] + p[2]), -windowHeight + columnSize * (p[1] + p[3])); //Ellipseに対しては右と下のマージンを削らなくてよい?
            }
        }
        public void GenerarColumnasDinamicas()
        {
            //Variables Auxiliares
            GridViewColumn          Columna;
            FrameworkElementFactory Txt;
            Assembly assembly;
            string   TipoDato;

            #region Columna Estatus Diagnostico

            //IList<MMaster> ListadoStatusDiagnostico = service.GetMMaster(new MMaster { MetaType = new MType { Code = "ESTATUSD" } });
            //Columna = new GridViewColumn();
            //assembly = Assembly.GetAssembly(Type.GetType("System.Windows.Controls.ComboBox, PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"));
            //TipoDato = "System.Windows.Controls.ComboBox";
            //Columna.Header = "Status Diagnostico";
            //Txt = new FrameworkElementFactory(assembly.GetType(TipoDato));
            //Txt.SetValue(ComboBox.ItemsSourceProperty, ListadoStatusDiagnostico);
            //Txt.SetValue(ComboBox.DisplayMemberPathProperty, "Name");
            //Txt.SetValue(ComboBox.SelectedValuePathProperty, "Code");
            //Txt.SetBinding(ComboBox.SelectedValueProperty, new System.Windows.Data.Binding("Estatus_Diagnostico"));
            //Txt.SetValue(ComboBox.WidthProperty, (double)110);


            //// add textbox template
            //Columna.CellTemplate = new DataTemplate();
            //Columna.CellTemplate.VisualTree = Txt;
            //View.ListadoEquipos.Columns.Add(Columna); //Creacion de la columna en el GridView
            //View.Model.ListRecords.Columns.Add("Estatus_Diagnostico", typeof(String)); //Creacion de la columna en el DataTable


            Columna        = new GridViewColumn();
            assembly       = Assembly.GetAssembly(Type.GetType("System.Windows.Controls.TextBlock, PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"));
            TipoDato       = "System.Windows.Controls.TextBlock";
            Columna.Header = "Status Diagnostico";
            Txt            = new FrameworkElementFactory(assembly.GetType(TipoDato));
            Txt.SetValue(TextBlock.MinWidthProperty, (double)100);
            Txt.SetBinding(TextBlock.TextProperty, new System.Windows.Data.Binding("Estatus_Diagnostico"));

            // add textbox template
            Columna.CellTemplate            = new DataTemplate();
            Columna.CellTemplate.VisualTree = Txt;
            View.ListadoEquipos.Columns.Add(Columna);                                  //Creacion de la columna en el GridView
            View.Model.ListRecords.Columns.Add("Estatus_Diagnostico", typeof(String)); //Creacion de la columna en el DataTable

            #endregion

            #region Columna Tipo Diagnostico

            Columna        = new GridViewColumn();
            assembly       = Assembly.GetAssembly(Type.GetType("System.Windows.Controls.TextBox, PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"));
            TipoDato       = "System.Windows.Controls.TextBox";
            Columna.Header = "Tipo Diagnostico";
            Txt            = new FrameworkElementFactory(assembly.GetType(TipoDato));
            Txt.SetValue(TextBox.MinWidthProperty, (double)100);
            Txt.SetBinding(TextBox.TextProperty, new System.Windows.Data.Binding("TIPO_DIAGNOSTICO"));
            Txt.SetValue(TextBox.TabIndexProperty, (int)0);//Interruption Point
            Txt.SetValue(TextBox.IsTabStopProperty, true);

            // add textbox template
            Columna.CellTemplate            = new DataTemplate();
            Columna.CellTemplate.VisualTree = Txt;
            View.ListadoEquipos.Columns.Add(Columna);                               //Creacion de la columna en el GridView
            View.Model.ListRecords.Columns.Add("TIPO_DIAGNOSTICO", typeof(String)); //Creacion de la columna en el DataTable

            #endregion

            #region Columna Falla Equipo

            IList <MMaster> ListadoFallaEquipoDiagnostico = service.GetMMaster(new MMaster {
                MetaType = new MType {
                    Code = "FALLADIR"
                }
            });
            Columna        = new GridViewColumn();
            assembly       = Assembly.GetAssembly(Type.GetType("System.Windows.Controls.ComboBox, PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"));
            TipoDato       = "System.Windows.Controls.ComboBox";
            Columna.Header = "Falla Equipo";
            Txt            = new FrameworkElementFactory(assembly.GetType(TipoDato));
            Txt.SetValue(ComboBox.ItemsSourceProperty, ListadoFallaEquipoDiagnostico);
            Txt.SetValue(ComboBox.DisplayMemberPathProperty, "Name");
            Txt.SetValue(ComboBox.SelectedValuePathProperty, "Code");
            Txt.SetBinding(ComboBox.SelectedValueProperty, new System.Windows.Data.Binding("FALLA_DIAGNOSTICO"));
            Txt.SetValue(ComboBox.WidthProperty, (double)110);
            Txt.SetBinding(ComboBox.TagProperty, new System.Windows.Data.Binding("Serial"));
            Txt.AddHandler(System.Windows.Controls.ComboBox.SelectionChangedEvent, new SelectionChangedEventHandler(OnValidarDiagnostico)); //NUEVO EVENTO

            // add textbox template
            Columna.CellTemplate            = new DataTemplate();
            Columna.CellTemplate.VisualTree = Txt;
            View.ListadoEquipos.Columns.Add(Columna);                                //Creacion de la columna en el GridView
            View.Model.ListRecords.Columns.Add("FALLA_DIAGNOSTICO", typeof(String)); //Creacion de la columna en el DataTable

            #endregion

            #region Columna SubFalla Equipo

            IList <MMaster> ListadosSubFallaEquipoDiagnostico = service.GetMMaster(new MMaster {
                MetaType = new MType {
                    Code = "SUBFALLA"
                }
            });
            Columna        = new GridViewColumn();
            assembly       = Assembly.GetAssembly(Type.GetType("System.Windows.Controls.ComboBox, PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"));
            TipoDato       = "System.Windows.Controls.ComboBox";
            Columna.Header = "Sub-Falla Equipo";
            Txt            = new FrameworkElementFactory(assembly.GetType(TipoDato));
            Txt.SetValue(ComboBox.ItemsSourceProperty, ListadosSubFallaEquipoDiagnostico);
            Txt.SetValue(ComboBox.DisplayMemberPathProperty, "Name");
            Txt.SetValue(ComboBox.SelectedValuePathProperty, "Name");
            Txt.SetBinding(ComboBox.SelectedValueProperty, new System.Windows.Data.Binding("SUBFALLA"));
            Txt.SetValue(ComboBox.WidthProperty, (double)110);

            // add textbox template
            Columna.CellTemplate            = new DataTemplate();
            Columna.CellTemplate.VisualTree = Txt;
            View.ListadoEquipos.Columns.Add(Columna);                       //Creacion de la columna en el GridView
            View.Model.ListRecords.Columns.Add("SUBFALLA", typeof(String)); //Creacion de la columna en el DataTable

            #endregion

            #region Columna Tecnico Diagnosticador

            //IList<Rol> ObtRol1 = service.GetRol(new Rol { RolCode = "DTVDIAG" });
            //String ObtRol = service.GetUserByRol(new UserByRol { Rol = (Rol)ObtRol1 }).Select(f => f.Rol).ToString();
            //IList<SysUser> ListadoTecnicoDiagnosticadorCalidad = service.GetSysUser(new SysUser { UserRols = (List<UserByRol>)ObtRol });

            IList <SysUser> ListadoTecnicoDiagnosticadorCalidad = service.GetSysUser(new SysUser());
            Columna        = new GridViewColumn();
            assembly       = Assembly.GetAssembly(Type.GetType("System.Windows.Controls.ComboBox, PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"));
            TipoDato       = "System.Windows.Controls.ComboBox";
            Columna.Header = "Tecnico";
            Txt            = new FrameworkElementFactory(assembly.GetType(TipoDato));
            Txt.SetValue(ComboBox.ItemsSourceProperty, ListadoTecnicoDiagnosticadorCalidad);
            Txt.SetValue(ComboBox.DisplayMemberPathProperty, "FullDesc");
            Txt.SetValue(ComboBox.SelectedValuePathProperty, "UserName");
            Txt.SetBinding(ComboBox.SelectedValueProperty, new System.Windows.Data.Binding("TECNICO_DIAG"));
            Txt.SetValue(ComboBox.WidthProperty, (double)110);

            // add textbox template
            Columna.CellTemplate            = new DataTemplate();
            Columna.CellTemplate.VisualTree = Txt;
            View.ListadoEquipos.Columns.Add(Columna);                           //Creacion de la columna en el GridView
            View.Model.ListRecords.Columns.Add("TECNICO_DIAG", typeof(String)); //Creacion de la columna en el DataTable

            #endregion

            #region Columna Nivel Candidato

            Columna        = new GridViewColumn();
            assembly       = Assembly.GetAssembly(Type.GetType("System.Windows.Controls.TextBlock, PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"));
            TipoDato       = "System.Windows.Controls.TextBlock";
            Columna.Header = "Nivel Candidato";
            Txt            = new FrameworkElementFactory(assembly.GetType(TipoDato));
            Txt.SetValue(TextBlock.MinWidthProperty, (double)100);
            Txt.SetBinding(TextBlock.TextProperty, new System.Windows.Data.Binding("NIVEL_CANDIDATO"));

            // add textbox template
            Columna.CellTemplate            = new DataTemplate();
            Columna.CellTemplate.VisualTree = Txt;
            View.ListadoEquipos.Columns.Add(Columna);                              //Creacion de la columna en el GridView
            View.Model.ListRecords.Columns.Add("NIVEL_CANDIDATO", typeof(String)); //Creacion de la columna en el DataTable

            #endregion
        }
        public SelectorColumn()
        {
            FieldName    = CheckedColumnFieldName;
            UnboundType  = UnboundColumnType.Boolean;
            EditSettings = new CheckEditSettings();
            Fixed        = FixedStyle.None;
            HorizontalHeaderContentAlignment = HorizontalAlignment.Center;

            #region Header Template

            DataTemplate            _template   = new DataTemplate();
            FrameworkElementFactory GridFactory = new FrameworkElementFactory(typeof(System.Windows.Controls.Grid));
            GridFactory.SetValue(System.Windows.Controls.Grid.HorizontalAlignmentProperty, HorizontalAlignment.Center);
            GridFactory.SetValue(System.Windows.Controls.Grid.VerticalAlignmentProperty, VerticalAlignment.Center);
            GridFactory.SetValue(System.Windows.Controls.Grid.VerticalAlignmentProperty, VerticalAlignment.Center);
            FrameworkElementFactory header = new FrameworkElementFactory(typeof(CheckEdit));
            header.SetValue(CheckEdit.VerticalAlignmentProperty, VerticalAlignment.Center);
            header.SetValue(CheckEdit.HorizontalAlignmentProperty, HorizontalAlignment.Center);
            header.AddHandler(CheckEdit.EditValueChangedEvent, new EditValueChangedEventHandler(chkHeader_EditValueChanged));

            Binding binding = new Binding
            {
                Path   = new PropertyPath("IsSelectAll"),
                Source = this,
                Mode   = BindingMode.TwoWay,
                NotifyOnSourceUpdated = true
            };

            Binding bindingHeaderVisibility = new Binding
            {
                Path   = new PropertyPath("HeaderVisibility"),
                Source = this,
                Mode   = BindingMode.TwoWay,
                NotifyOnSourceUpdated = true
            };

            header.SetBinding(CheckEdit.VisibilityProperty, bindingHeaderVisibility);
            header.SetBinding(CheckEdit.EditValueProperty, binding);
            GridFactory.AppendChild(header);
            _template.VisualTree = GridFactory;

            HeaderTemplate = _template;
            #endregion
            //< DataTemplate >
            //< CheckBox IsChecked = "{Binding RowData.Row.IsSelected}" IsEnabled = "{Binding RowData.Row.IsTest}" HorizontalAlignment = "Center" VerticalAlignment = "Center" />

            //</ DataTemplate >
            #region Cell Template
            DataTemplate            _cellTemplate   = new DataTemplate();
            FrameworkElementFactory cellGridFactory = new FrameworkElementFactory(typeof(System.Windows.Controls.Grid));
            cellGridFactory.SetValue(System.Windows.Controls.Grid.HorizontalAlignmentProperty, HorizontalAlignment.Stretch);
            cellGridFactory.SetValue(System.Windows.Controls.Grid.VerticalAlignmentProperty, VerticalAlignment.Stretch);

            FrameworkElementFactory cellFactory = new FrameworkElementFactory(typeof(CheckEdit));
            cellFactory.SetValue(CheckEdit.VerticalAlignmentProperty, VerticalAlignment.Center);
            cellFactory.SetValue(CheckEdit.HorizontalAlignmentProperty, HorizontalAlignment.Center);

            Binding cellBinding = new Binding
            {
                Path = new PropertyPath("RowData.Row.IsSelected")
                       //Mode = BindingMode.TwoWay
            };

            Binding cellReadBinding = new Binding
            {
                Path = new PropertyPath("RowData.Row.SelectReadOnly")
                       //Mode = BindingMode.TwoWay
            };

            Binding cellEnableBinding = new Binding
            {
                Path      = new PropertyPath("RowData.Row.SelectReadOnly"),
                Converter = new DevExpress.Xpf.Core.BoolInverseConverter()
                            //Mode = BindingMode.TwoWay
            };
            cellFactory.AddHandler(CheckEdit.EditValueChangedEvent, new EditValueChangedEventHandler(Cell_EditValueChanged));
            cellFactory.SetValue(CheckEdit.EditValueProperty, cellBinding);
            cellFactory.SetValue(CheckEdit.IsReadOnlyProperty, cellReadBinding);
            cellFactory.SetValue(CheckEdit.IsEnabledProperty, cellEnableBinding);


            cellGridFactory.AppendChild(cellFactory);
            _cellTemplate.VisualTree = cellGridFactory;

            CellTemplate = _cellTemplate;
            #endregion
        }
        /// <summary>
        /// Устанавливает заголовки
        /// </summary>
        protected virtual void SetHeaders()
        {
            if (!(itemsListView.View is GridView))
            {
                itemsListView.View = new GridView();
            }

            ColumnHeaderList.Clear();

            try
            {
                List <PropertyInfo> properties = GetTypeProperties();
                GridViewColumn      columnHeader;
                foreach (PropertyInfo propertyInfo in properties)
                {
                    ListViewDataAttribute attr =
                        (ListViewDataAttribute)propertyInfo.GetCustomAttributes(typeof(ListViewDataAttribute), false)[0];

                    #region Определение ЭУ

                    if (propertyInfo.PropertyType.IsSubclassOf(typeof(StaticDictionary)))
                    {
                        //object val = propertyInfo.GetValue(obj, null);

                        //if (propertyInfo.PropertyType.GetCustomAttributes(typeof(TableAttribute), false).Length > 0)
                        //{
                        //    DictionaryComboBox dc = new DictionaryComboBox
                        //    {
                        //        Enabled = controlEnabled,
                        //        Name = propertyInfo.Name,
                        //        SelectedItem = (StaticDictionary)val,
                        //        Tag = propertyInfo,
                        //        Type = propertyInfo.PropertyType,
                        //    };
                        //    //для возможности вызова новой вкладки
                        //    Program.MainDispatcher.ProcessControl(dc);
                        //    //
                        //    return dc;
                        //}
                        Type         t = propertyInfo.PropertyType;
                        PropertyInfo p = t.GetProperty("Items");

                        ConstructorInfo  ci       = t.GetConstructor(new Type[0]);
                        StaticDictionary instance = (StaticDictionary)ci.Invoke(null);

                        IEnumerable staticList = (IEnumerable)p.GetValue(instance, null);

                        DataTemplate            template = new DataTemplate();
                        FrameworkElementFactory factory  = new FrameworkElementFactory(typeof(System.Windows.Controls.ComboBox));
                        template.VisualTree = factory;

                        //System.Windows.Data.Binding sourceBinding = new System.Windows.Data.Binding();
                        //sourceBinding.Source = staticList;
                        //BindingOperations.SetBinding(taskItemListView, ListView.ItemsSourceProperty, sourceBinding );

                        factory.SetBinding(ItemsControl.ItemsSourceProperty, new System.Windows.Data.Binding {
                            Source = staticList
                        });

                        //childFactory = new FrameworkElementFactory(typeof(Label));

                        //childFactory.SetBinding(Label.ContentProperty, new Binding("Machine.Descriiption"));

                        //childFactory.SetValue(Label.WidthProperty, 170.0);

                        //childFactory.SetValue(Label.HorizontalAlignmentProperty, HorizontalAlignment.Center);

                        //factory.AppendChild(childFactory);
                        columnHeader = new GridViewColumn {
                            CellTemplate = template
                        };
                    }
                    else if (propertyInfo.PropertyType.IsSubclassOf(typeof(AbstractDictionary)))
                    {
                        IDictionaryCollection dc;
                        try
                        {
                            dc = GlobalObjects.CasEnvironment.Dictionaries[propertyInfo.PropertyType];
                        }
                        catch (Exception)
                        {
                            dc = null;
                        }

                        DataTemplate            template = new DataTemplate();
                        FrameworkElementFactory factory  = new FrameworkElementFactory(typeof(System.Windows.Controls.ComboBox));
                        template.VisualTree = factory;

                        //System.Windows.Data.Binding sourceBinding = new System.Windows.Data.Binding();
                        //sourceBinding.Source = staticList;
                        //BindingOperations.SetBinding(taskItemListView, ListView.ItemsSourceProperty, sourceBinding );

                        if (dc != null)
                        {
                            List <KeyValuePair <string, IDictionaryItem> > list = new List <KeyValuePair <string, IDictionaryItem> >();
                            foreach (IDictionaryItem item in dc)
                            {
                                list.Add(new KeyValuePair <string, IDictionaryItem>(item.ToString(), item));
                            }

                            factory.SetBinding(ItemsControl.ItemsSourceProperty, new System.Windows.Data.Binding {
                                Source = list
                            });
                            factory.SetBinding(ItemsControl.DisplayMemberPathProperty, new System.Windows.Data.Binding("Key"));
                            factory.SetBinding(ItemsControl.ItemsSourceProperty, new System.Windows.Data.Binding("Value"));
                        }

                        columnHeader = new GridViewColumn {
                            CellTemplate = template
                        };

                        //AbstractDictionary val = (AbstractDictionary)propertyInfo.GetValue(obj, null);
                        //DictionaryComboBox dc = new DictionaryComboBox
                        //{
                        //    Enabled = controlEnabled,
                        //    SelectedItem = val,
                        //    Tag = propertyInfo,
                        //    Type = propertyInfo.PropertyType,
                        //};
                        //для возможности вызова новой вкладки
                        //Program.MainDispatcher.ProcessControl(dc);
                        //
                        //return dc;
                    }
                    else if (propertyInfo.PropertyType.IsSubclassOf(typeof(BaseEntityObject)))
                    {
                        DataTemplate template = new DataTemplate();

                        FrameworkElementFactory factory = new FrameworkElementFactory(typeof(System.Windows.Controls.TextBox));
                        factory.SetValue(System.Windows.Controls.TextBox.TextWrappingProperty, TextWrapping.Wrap);
                        factory.SetValue(TextBoxBase.IsReadOnlyProperty, true);
                        factory.SetBinding(System.Windows.Controls.TextBox.TextProperty, new System.Windows.Data.Binding {
                            Source = list
                        });
                        template.VisualTree = factory;

                        columnHeader = new GridViewColumn {
                            CellTemplate = template
                        };
                    }
                    else if (propertyInfo.PropertyType.IsEnum)
                    {
                        DataTemplate            template = new DataTemplate();
                        FrameworkElementFactory factory  = new FrameworkElementFactory(typeof(System.Windows.Controls.ComboBox));
                        template.VisualTree = factory;

                        List <KeyValuePair <string, object> > list = new List <KeyValuePair <string, object> >();
                        foreach (object o in Enum.GetValues(propertyInfo.PropertyType))
                        {
                            string    name = Enum.GetName(propertyInfo.PropertyType, o);
                            string    desc = name;
                            FieldInfo fi   = propertyInfo.PropertyType.GetField(name);
                            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
                            if (attributes.Length > 0)
                            {
                                string s = attributes[0].Description;
                                if (!string.IsNullOrEmpty(s))
                                {
                                    desc = s;
                                }
                            }
                            list.Add(new KeyValuePair <string, object>(desc, o));
                        }

                        factory.SetBinding(ItemsControl.ItemsSourceProperty, new System.Windows.Data.Binding {
                            Source = list
                        });
                        factory.SetBinding(ItemsControl.DisplayMemberPathProperty, new System.Windows.Data.Binding("Key"));
                        factory.SetBinding(ItemsControl.ItemsSourceProperty, new System.Windows.Data.Binding("Value"));

                        columnHeader = new GridViewColumn {
                            CellTemplate = template
                        };
                    }
                    else
                    {
                        #region  ЭУ для базовых типов

                        string typeName = propertyInfo.PropertyType.Name.ToLower();
                        switch (typeName)
                        {
                        case "string":
                        {
                            DataTemplate template = new DataTemplate();

                            FrameworkElementFactory factory = new FrameworkElementFactory(typeof(System.Windows.Controls.TextBox));
                            factory.SetValue(System.Windows.Controls.TextBox.TextWrappingProperty, TextWrapping.Wrap);
                            factory.SetValue(TextBoxBase.IsReadOnlyProperty, true);
                            template.VisualTree = factory;

                            columnHeader = new GridViewColumn {
                                CellTemplate = template
                            };

                            break;
                        }

                        case "int32":
                        case "int16":
                        {
                            DataTemplate template = new DataTemplate();

                            FrameworkElementFactory factory = new FrameworkElementFactory(typeof(System.Windows.Controls.TextBox));
                            factory.SetValue(System.Windows.Controls.TextBox.TextWrappingProperty, TextWrapping.Wrap);
                            factory.SetValue(TextBoxBase.IsReadOnlyProperty, true);
                            template.VisualTree = factory;

                            columnHeader = new GridViewColumn {
                                CellTemplate = template
                            };

                            break;
                        }

                        case "datetime":
                        {
                            DataTemplate template = new DataTemplate();

                            FrameworkElementFactory factory = new FrameworkElementFactory(typeof(System.Windows.Controls.TextBox));
                            factory.SetValue(System.Windows.Controls.TextBox.TextWrappingProperty, TextWrapping.Wrap);
                            factory.SetValue(TextBoxBase.IsReadOnlyProperty, true);
                            template.VisualTree = factory;

                            columnHeader = new GridViewColumn {
                                CellTemplate = template
                            };
                            break;
                        }

                        case "bool":
                        case "boolean":
                        {
                            DataTemplate template = new DataTemplate();

                            FrameworkElementFactory factory = new FrameworkElementFactory(typeof(System.Windows.Controls.CheckBox));
                            template.VisualTree = factory;

                            columnHeader = new GridViewColumn {
                                CellTemplate = template
                            };

                            break;
                        }

                        case "double":
                        {
                            DataTemplate template = new DataTemplate();

                            FrameworkElementFactory factory = new FrameworkElementFactory(typeof(System.Windows.Controls.TextBox));
                            factory.SetValue(System.Windows.Controls.TextBox.TextWrappingProperty, TextWrapping.Wrap);
                            factory.SetValue(TextBoxBase.IsReadOnlyProperty, true);
                            template.VisualTree = factory;

                            columnHeader = new GridViewColumn {
                                CellTemplate = template
                            };

                            break;
                        }

                        //case "directivethreshold":
                        //    {
                        //        object val = propertyInfo.GetValue(obj, null);
                        //        return new DirectiveThresholdControl { Enabled = controlEnabled, Threshold = (DirectiveThreshold)val, Tag = propertyInfo };
                        //    }
                        //case "detaildirectivethreshold":
                        //    {
                        //        object val = propertyInfo.GetValue(obj, null);
                        //        return new DetailDirectiveThresholdControl { Enabled = controlEnabled, Threshold = (DetailDirectiveThreshold)val, Tag = propertyInfo };
                        //    }
                        //case "lifelength":
                        //    {
                        //        object val = propertyInfo.GetValue(obj, null);
                        //        return new LifelengthViewer
                        //        {
                        //            Enabled = controlEnabled,
                        //            Lifelength = (Lifelength)val,
                        //            MinimumSize = new Size(20, 17),
                        //            Tag = propertyInfo
                        //        };
                        //    }
                        default:
                            columnHeader = null;
                            break;
                        }
                        #endregion
                    }
                    #endregion

                    if (columnHeader == null)
                    {
                        continue;
                    }

                    columnHeader.Width  = (int)(attr.HeaderWidth < 1 ? itemsListView.Width * attr.HeaderWidth : attr.HeaderWidth);
                    columnHeader.Header = attr.Title;
                    //columnHeader.Tag = propertyInfo;
                    //Поиск NotNullAttribute для определения возможности задавать пустые значения в колонке
                    //NotNullAttribute notNullAttribute =
                    //    (NotNullAttribute)propertyInfo.GetCustomAttributes(typeof(NotNullAttribute), false).FirstOrDefault();
                    //if (notNullAttribute != null)
                    //{
                    //    //Если имеется атрибут NotNullAttribute то шрифт заголовка задается Жирным
                    //    columnHeader.HeaderCell.Style.Font = new Font(dataGridView.ColumnHeadersDefaultCellStyle.Font, FontStyle.Bold);
                    //    columnHeader.HeaderCell.ToolTipText =
                    //        string.Format("The cells in column {0} should be filled", columnHeader.HeaderText);
                    //}
                    ColumnHeaderList.Add(columnHeader);
                }
            }
            catch (Exception ex)
            {
                Program.Provider.Logger.Log("Error while building list headers", ex);
                return;
            }
        }
Exemple #26
0
        public static void SetParametry(WindowPosition wp, bool state, DependencyObject element)
        {
            FrameworkElementFactory root;

            if (!state)
            {
                root = new FrameworkElementFactory(typeof(StackPanel));

                switch (wp)
                {
                case WindowPosition.Left:
                case WindowPosition.LeftTop:
                case WindowPosition.LeftBottom:
                    root.SetValue(StackPanel.OrientationProperty, Orientation.Vertical);
                    SetFlow(element, FlowDirection.RightToLeft);
                    SetVScrollBarVisibility(element, ScrollBarVisibility.Auto);
                    SetHScrollBarVisibility(element, ScrollBarVisibility.Disabled);
                    break;

                case WindowPosition.Right:
                case WindowPosition.RightTop:
                case WindowPosition.RightBottom:
                    root.SetValue(StackPanel.OrientationProperty, Orientation.Vertical);
                    SetFlow(element, FlowDirection.LeftToRight);
                    SetVScrollBarVisibility(element, ScrollBarVisibility.Auto);
                    SetHScrollBarVisibility(element, ScrollBarVisibility.Disabled);
                    break;

                case WindowPosition.Top:
                    root.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
                    SetFlow(element, FlowDirection.LeftToRight);
                    SetVScrollBarVisibility(element, ScrollBarVisibility.Disabled);
                    SetHScrollBarVisibility(element, ScrollBarVisibility.Auto);
                    break;

                case WindowPosition.Bottom:
                    root.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
                    SetFlow(element, FlowDirection.LeftToRight);
                    SetVScrollBarVisibility(element, ScrollBarVisibility.Disabled);
                    SetHScrollBarVisibility(element, ScrollBarVisibility.Auto);
                    break;

                case WindowPosition.None:
                    root = new FrameworkElementFactory(typeof(WrapPanel));
                    root.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
                    SetFlow(element, FlowDirection.LeftToRight);
                    SetVScrollBarVisibility(element, ScrollBarVisibility.Auto);
                    SetHScrollBarVisibility(element, ScrollBarVisibility.Disabled);
                    break;
                }
            }
            else
            {
                root = new FrameworkElementFactory(typeof(WrapPanel));

                switch (wp)
                {
                case WindowPosition.Left:
                case WindowPosition.LeftTop:
                case WindowPosition.LeftBottom:
                    root.SetValue(WrapPanel.OrientationProperty, Orientation.Vertical);
                    SetFlow(element, FlowDirection.LeftToRight);
                    SetVScrollBarVisibility(element, ScrollBarVisibility.Disabled);
                    SetHScrollBarVisibility(element, ScrollBarVisibility.Auto);
                    break;

                case WindowPosition.Right:
                case WindowPosition.RightTop:
                case WindowPosition.RightBottom:
                    root.SetValue(WrapPanel.OrientationProperty, Orientation.Vertical);
                    SetFlow(element, FlowDirection.RightToLeft);
                    SetVScrollBarVisibility(element, ScrollBarVisibility.Disabled);
                    SetHScrollBarVisibility(element, ScrollBarVisibility.Auto);
                    break;

                case WindowPosition.Top:
                    root.SetValue(WrapPanel.OrientationProperty, Orientation.Horizontal);
                    SetFlow(element, FlowDirection.LeftToRight);
                    SetVScrollBarVisibility(element, ScrollBarVisibility.Auto);
                    SetHScrollBarVisibility(element, ScrollBarVisibility.Disabled);
                    break;

                case WindowPosition.Bottom:
                    root.SetValue(WrapPanel.OrientationProperty, Orientation.Horizontal);
                    SetFlow(element, FlowDirection.LeftToRight);
                    SetVScrollBarVisibility(element, ScrollBarVisibility.Auto);
                    SetHScrollBarVisibility(element, ScrollBarVisibility.Disabled);
                    break;

                case WindowPosition.None:
                    root.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
                    SetFlow(element, FlowDirection.LeftToRight);
                    SetVScrollBarVisibility(element, ScrollBarVisibility.Auto);
                    SetHScrollBarVisibility(element, ScrollBarVisibility.Disabled);
                    break;
                }
            }

            SetItemsPanel(element, new ItemsPanelTemplate(root));
        }
Exemple #27
0
        public static void CurrentSortColumnSetGlyph(GridViewColumn gvc, ListView lv)
        {
            ListSortDirection lsd;
            Brush             brush;

            if (lv == null)
            {
                lsd   = ListSortDirection.Ascending;
                brush = Brushes.Transparent;
            }
            else
            {
                SortDescriptionCollection sdc = lv.Items.SortDescriptions;
                if (sdc == null || sdc.Count < 1)
                {
                    return;
                }

                lsd   = sdc[0].Direction;
                brush = Brushes.Gray;
            }

            FrameworkElementFactory fefGlyph = new FrameworkElementFactory(typeof(Path));

            fefGlyph.Name = "arrow";
            fefGlyph.SetValue(Path.StrokeThicknessProperty, 1.0);
            fefGlyph.SetValue(Path.FillProperty, brush);
            fefGlyph.SetValue(StackPanel.HorizontalAlignmentProperty, HorizontalAlignment.Center);

            int s = 4;

            if (lsd == ListSortDirection.Ascending)
            {
                PathFigure pf = new PathFigure();
                pf.IsClosed   = true;
                pf.StartPoint = new Point(0, s);
                pf.Segments.Add(new LineSegment(new Point(s * 2, s), false));
                pf.Segments.Add(new LineSegment(new Point(s, 0), false));

                PathGeometry pg = new PathGeometry();
                pg.Figures.Add(pf);

                fefGlyph.SetValue(Path.DataProperty, pg);
            }
            else
            {
                PathFigure pf = new PathFigure();
                pf.IsClosed   = true;
                pf.StartPoint = new Point(0, 0);
                pf.Segments.Add(new LineSegment(new Point(s, s), false));
                pf.Segments.Add(new LineSegment(new Point(s * 2, 0), false));

                PathGeometry pg = new PathGeometry();
                pg.Figures.Add(pf);

                fefGlyph.SetValue(Path.DataProperty, pg);
            }

            FrameworkElementFactory fefTextBlock = new FrameworkElementFactory(typeof(TextBlock));

            fefTextBlock.SetValue(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Center);
            fefTextBlock.SetValue(TextBlock.TextProperty, new Binding());

            FrameworkElementFactory fefDockPanel = new FrameworkElementFactory(typeof(StackPanel));

            fefDockPanel.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
            fefDockPanel.AppendChild(fefTextBlock);
            fefDockPanel.AppendChild(fefGlyph);

            DataTemplate dt = new DataTemplate(typeof(GridViewColumn));

            dt.VisualTree = fefDockPanel;

            gvc.HeaderTemplate = dt;
        }
Exemple #28
0
        private void initializeColumns()
        {
            var specObjectType = content.SpecTypes.FirstOrDefault(x => x.GetType() == typeof(SpecObjectType));
            int chapterIndex   = specObjectType?.SpecAttributes.FindIndex(x => x.LongName == "ReqIF.ChapterName") ?? -1;
            int textIndex      = specObjectType?.SpecAttributes.FindIndex(x => x.LongName == "ReqIF.Text") ?? -1;

            int i = 0;

            if (chapterIndex >= 0 && textIndex >= 0)
            {
                DataGridTemplateColumn col = new DataGridTemplateColumn();
                col.Header = FindResource("requirement");

                col.CellTemplateSelector = new HtmlCellTemplateSelector(chapterIndex, textIndex);
                col.Width = 500;
                MainDataGrid.Columns.Add(col);
            }
            foreach (var dataType in content.SpecTypes.Where(x => x.GetType() == typeof(SpecObjectType)).FirstOrDefault().SpecAttributes)
            {
                FrameworkElementFactory factory = null;
                DependencyProperty      dp      = null;
                if (chapterIndex == i || textIndex == i)
                {
                    i++;
                    continue;
                }

                Type typeOfDataType = dataType.DatatypeDefinition.GetType();
                if (typeOfDataType == typeof(DatatypeDefinitionEnumeration))
                {
                    factory = new FrameworkElementFactory(typeof(ListView));
                    dp      = ListView.ItemsSourceProperty;
                    //Itemtemplate for EnumValue
                    FrameworkElementFactory subfactory = new FrameworkElementFactory(typeof(TextBlock));
                    subfactory.SetBinding(TextBlock.TextProperty, new Binding("LongName")
                    {
                        Mode = BindingMode.OneWay,
                        NotifyOnSourceUpdated = true,
                        UpdateSourceTrigger   = UpdateSourceTrigger.PropertyChanged
                    });
                    DataTemplate dt = new DataTemplate()
                    {
                        VisualTree = subfactory
                    };
                    factory.SetValue(ListView.ItemTemplateProperty, dt);
                }
                else if (typeOfDataType == typeof(DatatypeDefinitionBoolean))
                {
                    factory = new FrameworkElementFactory(typeof(System.Windows.Controls.CheckBox));
                    dp      = System.Windows.Controls.CheckBox.IsCheckedProperty;
                    factory.SetValue(System.Windows.Controls.CheckBox.HorizontalAlignmentProperty, HorizontalAlignment.Center);
                }
                else if (typeOfDataType == typeof(DatatypeDefinitionString))
                {
                    factory = new FrameworkElementFactory(typeof(TextBlock));
                    dp      = TextBlock.TextProperty;
                }
                else if (typeOfDataType == typeof(DatatypeDefinitionInteger))
                {
                    factory = new FrameworkElementFactory(typeof(TextBlock));
                    dp      = TextBlock.TextProperty;
                }
                else if (typeOfDataType == typeof(DatatypeDefinitionReal))
                {
                    factory = new FrameworkElementFactory(typeof(TextBlock));
                    dp      = TextBlock.TextProperty;
                }
                else if (typeOfDataType == typeof(DatatypeDefinitionXHTML))
                {
                    factory = new FrameworkElementFactory(typeof(Html));
                    dp      = Html.HtmlProperty;
                }
                else if (typeOfDataType == typeof(DatatypeDefinitionDate))
                {
                    factory = new FrameworkElementFactory(typeof(TextBlock));
                    dp      = TextBlock.TextProperty;
                }
                factory.SetValue(IsEnabledProperty, false);
                var binding = new Binding("Values[" + i++ + "].AttributeValue.ObjectValue");
                binding.Mode = BindingMode.OneWay;
                if (typeOfDataType == typeof(DatatypeDefinitionXHTML))
                {
                    binding.Converter = new XHTMLConverter();
                }
                factory.SetBinding(dp, binding);

                DataGridTemplateColumn dataGridTemplateColumn = new DataGridTemplateColumn()
                {
                    Header       = dataType.LongName,
                    CellTemplate = new DataTemplate()
                    {
                        VisualTree = factory
                    }
                };
                if (typeOfDataType == typeof(DatatypeDefinitionXHTML))
                {
                    dataGridTemplateColumn.Width = 300;
                }
                MainDataGrid.Columns.Add(dataGridTemplateColumn);
            }
        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var columns = new ObservableCollection <DataGridColumn>();
            var dv      = value as DataView;

            if (dv != null)
            {
                var dg = new DataGrid();

                //var gridView = new GridView();
                var cols = dv.ToTable().Columns;
                foreach (DataColumn item in cols)
                {
                    // This section turns off the RecogniseAccessKey setting in the column header
                    // which allows it to display underscores correctly.
                    var hdrTemplate      = new DataTemplate();
                    var contentPresenter = new FrameworkElementFactory(typeof(Border));
                    contentPresenter.SetValue(ContentPresenter.RecognizesAccessKeyProperty, false);
                    var txtBlock = new FrameworkElementFactory(typeof(TextBlock));

                    txtBlock.SetValue(TextBlock.TextProperty, item.Caption);
                    txtBlock.SetValue(TextBlock.TextWrappingProperty, TextWrapping.WrapWithOverflow);
                    if (item.DataType != typeof(string))
                    {
                        txtBlock.SetValue(TextBlock.TextAlignmentProperty, TextAlignment.Right);
                    }

                    contentPresenter.AppendChild(txtBlock);
                    hdrTemplate.VisualTree = contentPresenter;

                    var bindingPath = FixBindingPath(item.ColumnName);

                    var cellTemplate = new DataTemplate();
                    if (item.DataType == typeof(Byte[]))
                    {
                        var style = new Style {
                            TargetType = typeof(ToolTip)
                        };

                        //style.Setters.Add(new Setter { Property = TemplateProperty, Value = GetToolTip(dataTable) });
                        //style.Setters.Add(new Setter { Property = OverridesDefaultStyleProperty, Value = true });
                        //style.Setters.Add(new Setter { Property = System.Windows.Controls.ToolTip.HasDropShadowProperty, Value = true });
                        //Resources.Add(typeof(ToolTip), style);

                        var cellImgBlock   = new FrameworkElementFactory(typeof(Image));
                        var cellTooltip    = new FrameworkElementFactory(typeof(ToolTip));
                        var cellImgTooltip = new FrameworkElementFactory(typeof(Image));
                        cellImgTooltip.SetValue(Image.WidthProperty, 150d);

                        cellImgBlock.SetValue(FrameworkContentElement.ToolTipProperty, cellTooltip);
                        cellTooltip.SetValue(ToolTip.ContentProperty, cellImgTooltip);

                        // Adding square brackets around the bind will escape any column names with the following "special" binding characters   . / ( ) [ ]
                        cellImgBlock.SetBinding(Image.SourceProperty, new Binding(bindingPath));
                        cellImgTooltip.SetBinding(Image.SourceProperty, new Binding(bindingPath));
                        cellImgBlock.SetValue(Image.WidthProperty, 50d);

                        cellTemplate.VisualTree = cellImgBlock;
                    }
                    else
                    {
                        var cellTxtBlock = new FrameworkElementFactory(typeof(TextBlock));
                        // Adding square brackets around the bind will escape any column names with the following "special" binding characters   . / ( ) [ ]
                        var colBinding = new Binding(bindingPath);
                        cellTxtBlock.SetBinding(TextBlock.TextProperty, colBinding);

                        // Bind FormatString if it exists
                        if (item.ExtendedProperties[Constants.FORMAT_STRING] != null)
                        {
                            colBinding.StringFormat = item.ExtendedProperties[Constants.FORMAT_STRING].ToString();
                        }
                        // set culture if it exists
                        if (item.ExtendedProperties[Constants.LOCALE_ID] != null)
                        {
                            var cultureInfo = CultureInfo.InvariantCulture;
                            try
                            {
                                cultureInfo = new CultureInfo((int)item.ExtendedProperties[Constants.LOCALE_ID]);
                            }
                            catch {
                                // Do Nothing, just use the initialized value for cultureInfo
                            }
                            colBinding.ConverterCulture = cultureInfo;
                        }
                        cellTxtBlock.SetValue(TextBlock.TextTrimmingProperty, TextTrimming.CharacterEllipsis);
                        if (item.DataType != typeof(string))
                        {
                            cellTxtBlock.SetValue(TextBlock.TextAlignmentProperty, TextAlignment.Right);
                        }
                        cellTxtBlock.SetBinding(FrameworkElement.ToolTipProperty, colBinding);
                        cellTemplate.VisualTree = cellTxtBlock;
                    }

                    var dgc = new DataGridTemplateColumn
                    {
                        CellTemplate = cellTemplate,
                        //    Width = Double.NaN,
                        HeaderTemplate          = hdrTemplate,
                        Header                  = item.Caption,
                        SortMemberPath          = item.ColumnName,
                        ClipboardContentBinding = new Binding(bindingPath)
                    };

                    columns.Add(dgc);
                    //dg.Columns.Add(gvc);
                }

                return(columns);
            }
            return(Binding.DoNothing);
        }
Exemple #30
0
        private void AddColumns()
        {
            SessionInfo.BatchIndex++;
            DataGridTemplateColumn _DataGridTemplateColumn = new DataGridTemplateColumn()
            {
                Header = "检测项目", Width = new DataGridLength(100, DataGridLengthUnitType.Star)
            };
            var TestItems = new TestItemController().GetActiveTestItemConfigurations();
            FrameworkElementFactory _StackPanel = new FrameworkElementFactory(typeof(StackPanel));

            _StackPanel.SetValue(StackPanel.VerticalAlignmentProperty, System.Windows.VerticalAlignment.Center);
            _StackPanel.SetValue(StackPanel.HorizontalAlignmentProperty, System.Windows.HorizontalAlignment.Center);
            _StackPanel.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
            foreach (TestingItemConfiguration _TestingItem in TestItems)
            {
                FrameworkElementFactory checkBox = new FrameworkElementFactory(typeof(CheckBox));
                checkBox.SetValue(CheckBox.DataContextProperty, _TestingItem);
                checkBox.SetValue(CheckBox.MarginProperty, new System.Windows.Thickness(5, 0, 5, 0));
                checkBox.SetValue(CheckBox.IsCheckedProperty, false);
                checkBox.SetValue(CheckBox.ContentProperty, _TestingItem.TestingItemName);

                checkBox.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(checkBox_Checked));
                checkBox.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(checkBox_Unchecked));
                _StackPanel.AppendChild(checkBox);

                TextBlock textBlock = new TextBlock();
                textBlock.Height = 16;
                textBlock.Margin = new Thickness(5, 0, 0, 0);
                textBlock.Width  = 16;
                textBlock.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                textBlock.VerticalAlignment   = System.Windows.VerticalAlignment.Center;
                textBlock.Background          = new SolidColorBrush((Color)ColorConverter.ConvertFromString(_TestingItem.TestingItemColor));
                sp_pointout.Children.Add(textBlock);

                Label label = new Label();
                label.Content             = _TestingItem.TestingItemName;
                label.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                label.VerticalAlignment   = System.Windows.VerticalAlignment.Center;
                label.Width = 65;
                sp_pointout.Children.Add(label);
            }
            DataTemplate dataTemplate = new DataTemplate();

            dataTemplate.VisualTree = _StackPanel;
            _DataGridTemplateColumn.CellTemplate = dataTemplate;
            dg_TubesGroup.Columns.Insert(2, _DataGridTemplateColumn);

            PoolingRules = new WanTai.Controller.PoolingRulesConfigurationController().GetPoolingRulesConfiguration();
            List <LiquidType> LiquidTypeList = SessionInfo.LiquidTypeList = WanTai.Common.Configuration.GetLiquidTypes();
            StringBuilder     stringBuilder  = new StringBuilder();

            foreach (LiquidType _LiquidType in LiquidTypeList)
            {
                if (_LiquidType.TypeId == 1)
                {
                    txt_Complement.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(_LiquidType.Color));
                    lab_Complement.Content    = _LiquidType.TypeName;
                }
                if (_LiquidType.TypeId == 2)
                {
                    txt_PositiveControl.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(_LiquidType.Color));
                    lab_PositiveControl.Content    = _LiquidType.TypeName;
                }
                if (_LiquidType.TypeId == 3)
                {
                    txt_NegativeControl.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(_LiquidType.Color));
                    lab_NegativeControl.Content    = _LiquidType.TypeName;
                }
                stringBuilder.Append(_LiquidType.TypeName + "、");
            }
            if (stringBuilder.ToString().Length > 0)
            {
                lab_tip.Content = "(" + stringBuilder.ToString().Substring(0, stringBuilder.ToString().Length - 1) + "不能分组!)";
            }
            //  dg_TubesGroup.ItemsSource = (TubeGroupList=new List<TubeGroup>());
            //<TextBlock Height="20" Margin="5,0,0,0"  Width="20" Grid.Row="1" Name="txt_NegativeControl" HorizontalAlignment="Left"  Background="LightGray" VerticalAlignment="Center" />
            //      <Label Content="阴性对照物" Name="lab_NegativeControl" Grid.Row="1" HorizontalAlignment="Left"   VerticalAlignment="Center" />
            // StringBuilder SBuilder = new StringBuilder();
            //SBuilder.Append("<DataGridTemplateColumn ");
            //SBuilder.Append("xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' ");
            //SBuilder.Append("xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' ");
            //SBuilder.Append("xmlns:local='clr-namespace:WanTai.View;assembly=WanTai.View' ");
            //SBuilder.Append("Header=\"混样模式\" Width=\"120\" >");
            //SBuilder.Append("<DataGridTemplateColumn.CellTemplate>");
            //SBuilder.Append("<DataTemplate >");
            //SBuilder.Append(" <ComboBox Name=\"cb_PoolingRulesConfigurations\" HorizontalAlignment=\"Stretch\" SelectedIndex=\"0\" SelectedValue=\"{Binding PoolingRulesID}\" SelectedValuePath=\"PoolingRulesID\" DisplayMemberPath=\"PoolingRulesName\"  ItemsSource=\"{Binding Source={StaticResource PoolingRulesConfigurations }}\" VerticalAlignment=\"Stretch\"  />");
            //SBuilder.Append("</DataTemplate>");
            //SBuilder.Append("</DataGridTemplateColumn.CellTemplate>");
            //SBuilder.Append("</DataGridTemplateColumn>");

            //SBuilder.Append("<DataGridTemplateColumn ");
            //SBuilder.Append("xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' ");
            //SBuilder.Append("xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' ");
            //SBuilder.Append("xmlns:local='clr-namespace:WanTai.View;assembly=WanTai.View' ");
            //SBuilder.Append("Header=\"检测项目\" Width=\"200\" >");
            //SBuilder.Append("<DataGridTemplateColumn.CellTemplate>");
            //SBuilder.Append("<DataTemplate >");
            //SBuilder.Append("<StackPanel HorizontalAlignment=\"Center\"  VerticalAlignment=\"Center\"  >");

            //SBuilder.Append("</StackPanel>");
            //SBuilder.Append("</DataTemplate>");
            //SBuilder.Append("</DataGridTemplateColumn.CellTemplate>");
            //SBuilder.Append("</DataGridTemplateColumn>");

            //Stream stream = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(SBuilder.ToString()));
            //DataGridTemplateColumn colIcon = XamlReader.Load(stream) as DataGridTemplateColumn;
            //this.dg_TubesGroup.Columns.Insert(1, colIcon);
            //SBuilder.Append("<DataGridTemplateColumn ");
            //SBuilder.Append("xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' ");
            //SBuilder.Append("xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' ");
            //SBuilder.Append("xmlns:local='clr-namespace:WanTai.View;assembly=WanTai.View' ");
            //SBuilder.Append("Header=\"操作\" Width=\"100\">");
            //SBuilder.Append(" <DataGridTemplateColumn.CellTemplate>");
            //SBuilder.Append("<DataTemplate >");
            //SBuilder.Append("<StackPanel Orientation=\"Horizontal\"  HorizontalAlignment=\"Center\" VerticalAlignment=\"Center\" >");
            //SBuilder.Append("<Button Content=\"删除\" Height=\"26\" Width=\"75\" HorizontalAlignment=\"Center\" Click=\"btn_del_Click\"  Name=\"btn_del\" VerticalAlignment=\"Center\"  />");
            //SBuilder.Append(" </StackPanel>");
            //SBuilder.Append("</DataTemplate>");
            //SBuilder.Append("</DataGridTemplateColumn.CellTemplate>");
            //SBuilder.Append("</DataGridTemplateColumn>");
            //SBuilder.Append("<DataGridTemplateColumn ");
            //SBuilder.Append("xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' ");
            //SBuilder.Append("xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' ");
            //SBuilder.Append("xmlns:local='clr-namespace:WanTai.View;assembly=WanTai.View' ");

            //SBuilder.Append("Header=\"采血管\" Width=\"*\" >");
            //SBuilder.Append("<DataGridTemplateColumn.CellTemplate>");
            //SBuilder.Append(" <DataTemplate >");
            //SBuilder.Append("<StackPanel Orientation=\"Horizontal\"  HorizontalAlignment=\"Left\" VerticalAlignment=\"Center\" >");
            //SBuilder.Append(" <Label Content=\"{Binding Path=TubesPosition}\" HorizontalAlignment=\"Left\"  Name=\"lab_TubesPosition\" VerticalAlignment=\"Center\" />");
            //SBuilder.Append("</StackPanel>");
            //SBuilder.Append("</DataTemplate>");
            //SBuilder.Append("</DataGridTemplateColumn.CellTemplate>");
            //SBuilder.Append("</DataGridTemplateColumn>");


            //Stream stream = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(SBuilder.ToString()));
            //  DataGridTemplateColumn colIcon = XamlReader.Load(stream) as DataGridTemplateColumn;
            //  colIcon.Header = i.ToString();
            // dg_Bules.Columns.Add(colIcon);
        }
        private static DataTemplate CreateDefaultEffectDataTemplate(UIElement target, BitmapImage effectIcon, string effectText, string destinationText)
        {
            if (!GetUseDefaultEffectDataTemplate(target))
            {
                return(null);
            }

            // Add icon
            var imageFactory = new FrameworkElementFactory(typeof(Image));

            imageFactory.SetValue(Image.SourceProperty, effectIcon);
            imageFactory.SetValue(FrameworkElement.HeightProperty, 12.0);
            imageFactory.SetValue(FrameworkElement.WidthProperty, 12.0);
            imageFactory.SetValue(FrameworkElement.MarginProperty, new Thickness(0.0, 0.0, 3.0, 0.0));

            // Add effect text
            var effectTextBlockFactory = new FrameworkElementFactory(typeof(TextBlock));

            effectTextBlockFactory.SetValue(TextBlock.TextProperty, effectText);
            effectTextBlockFactory.SetValue(TextBlock.FontSizeProperty, 11.0);
            effectTextBlockFactory.SetValue(TextBlock.ForegroundProperty, Brushes.Blue);

            // Add destination text
            var destinationTextBlockFactory = new FrameworkElementFactory(typeof(TextBlock));

            destinationTextBlockFactory.SetValue(TextBlock.TextProperty, destinationText);
            destinationTextBlockFactory.SetValue(TextBlock.FontSizeProperty, 11.0);
            destinationTextBlockFactory.SetValue(TextBlock.ForegroundProperty, Brushes.DarkBlue);
            destinationTextBlockFactory.SetValue(TextBlock.MarginProperty, new Thickness(3, 0, 0, 0));
            destinationTextBlockFactory.SetValue(TextBlock.FontWeightProperty, FontWeights.DemiBold);

            // Create containing panel
            var stackPanelFactory = new FrameworkElementFactory(typeof(StackPanel));

            stackPanelFactory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
            stackPanelFactory.SetValue(FrameworkElement.MarginProperty, new Thickness(2.0));
            stackPanelFactory.AppendChild(imageFactory);
            stackPanelFactory.AppendChild(effectTextBlockFactory);
            stackPanelFactory.AppendChild(destinationTextBlockFactory);

            // Add border
            var borderFactory  = new FrameworkElementFactory(typeof(Border));
            var stopCollection = new GradientStopCollection {
                new GradientStop(Colors.White, 0.0),
                new GradientStop(Colors.AliceBlue, 1.0)
            };
            var gradientBrush = new LinearGradientBrush(stopCollection)
            {
                StartPoint = new Point(0, 0),
                EndPoint   = new Point(0, 1)
            };

            borderFactory.SetValue(Panel.BackgroundProperty, gradientBrush);
            borderFactory.SetValue(Border.BorderBrushProperty, Brushes.DimGray);
            borderFactory.SetValue(Border.CornerRadiusProperty, new CornerRadius(3.0));
            borderFactory.SetValue(Border.BorderThicknessProperty, new Thickness(1.0));
            borderFactory.AppendChild(stackPanelFactory);

            // Finally add content to template
            var template = new DataTemplate();

            template.VisualTree = borderFactory;
            return(template);
        }
        private void updateAllPins()
        {
            if (this.customPins != null)
            {
                int nOdx   = 0;
                int nCount = 0;

                // this.nativeMap.Children.Clear();
                // this.nativeMap.MapElements.Clear();

                nCount = this.customPins.Count;
                for (nOdx = 0; nOdx < nCount; nOdx++)
                {
                    string sPinLabel = this.customPins[nOdx].Latitude.ToString("F2").Substring(0, 2);
                    MapControl.Location        aLoc     = new MapControl.Location(this.customPins[nOdx].Latitude, this.customPins[nOdx].Longitude);
                    System.Windows.Media.Brush pinBrush = System.Windows.Media.Brushes.Blue;
                    if (this.customPins[nOdx].BluePin)
                    {
                        pinBrush = System.Windows.Media.Brushes.Blue;
                    }
                    else
                    {
                        /** Orange Push Pin */
                        pinBrush = System.Windows.Media.Brushes.Orange;
                    }

                    ObservableCollection <Point> somePushpins = new ObservableCollection <Point>();
                    // ObservableCollection<MapControl.Pushpin> somePushpins = new ObservableCollection<MapControl.Pushpin>();

                    /**
                     * From Xaml Map Control github code (codeplex)
                     *  Pushpins = new ObservableCollection<Point>();
                     *  Pushpins.Add(
                     *      new Point
                     *      {
                     *          Name = "WHV - Eckwarderhörne",
                     *          Location = new Location(53.5495, 8.1877)
                     *      });
                     **/

                    Point aPushPin = new Point {
                        // MapControl.Pushpin aPushPin = new MapControl.Pushpin
                        Name     = sPinLabel,
                        Location = new MapControl.Location(aLoc.Latitude, aLoc.Longitude)
                                   //Content = sPinLabel,
                                   //// Location = new MapControl.Location(42.2917° N, 85.5872° W),
                                   //Location = aLoc,
                                   //Foreground = System.Windows.Media.Brushes.Black,
                                   //Visibility = Visibility.Visible
                    };

                    System.Windows.Style style = new System.Windows.Style {
                        TargetType = typeof(MapItem)
                    };
                    // style.Setters.Add(new EventSetter(MapItem.TouchDownEvent, new RoutedEventHandler( Map2ItemTouchDown )));
                    // style.Setters.Add(new System.Windows.Setter( MapItem.LocationProperty, aLoc));
                    style.Setters.Add(new System.Windows.Setter(MapPanel.LocationProperty, aLoc));
                    style.Setters.Add(new System.Windows.Setter(MapItem.VerticalContentAlignmentProperty, System.Windows.VerticalAlignment.Bottom));
                    style.Setters.Add(new System.Windows.Setter(MapItem.ForegroundProperty, System.Windows.Media.Brushes.Black));
                    style.Setters.Add(new System.Windows.Setter(MapItem.BackgroundProperty, pinBrush));
                    style.Setters.Add(new System.Windows.Setter(MapItem.VisibilityProperty, System.Windows.Visibility.Visible));
                    System.Windows.FrameworkElementFactory aPin = new FrameworkElementFactory(typeof(MapControl.Pushpin));
                    aPin.SetValue(MapControl.Pushpin.ContentProperty, sPinLabel);
                    aPin.SetValue(MapControl.Pushpin.ForegroundProperty, System.Windows.Media.Brushes.Black);
                    aPin.SetValue(MapControl.Pushpin.BackgroundProperty, pinBrush);
                    System.Windows.Controls.ControlTemplate ct = new System.Windows.Controls.ControlTemplate(typeof(MapControl.MapItem));
                    ct.VisualTree = aPin;
                    style.Setters.Add(new System.Windows.Setter(MapItem.TemplateProperty, ct));

                    somePushpins.Add(aPushPin);
                    //map.Children.Add(new MapItemsControl { ItemsSource=somePushpins, ItemContainerStyle = MainWindow.PushpinItemStyle });

                    MapControl.MapItemsControl aControl = new MapItemsControl {
                        ItemsSource                   = somePushpins,
                        ItemContainerStyle            = style,
                        IsSynchronizedWithCurrentItem = true
                    };

                    //MapControl.Pushpin aPushPinA = new Pushpin {
                    //    Content = "My Push Pin A",
                    //    Location = new MapControl.Location(21.821, 33.286),
                    //    Foreground = System.Windows.Media.Brushes.Blue,
                    //    Visibility = Visibility.Visible
                    //};

                    // map.Children.Add(aPushPinA);
                    Control.Children.Add(aControl);
                    //// MapControl.Location aLoc = new MapControl.Location(this.customPins[nOdx].Latitude, this.customPins[nOdx].Longitude);
                    //// if (this.customPins[nOdx].BluePin) {
                    ////System.Windows.Media.Color aColorBlue = System.Windows.Media.Color.FromRgb(0, 0, 255);
                    ////System.Windows.Media.Color aColorWhite = System.Windows.Media.Color.FromRgb(255, 255, 255);
                    ////MapControl.Pushpin aPin = new MapControl.Pushpin {
                    ////    Location = aLoc,
                    ////    Background = new System.Windows.Media.SolidColorBrush(aColorBlue),
                    ////    Foreground = new System.Windows.Media.SolidColorBrush(aColorWhite)
                    ////};
                    //Xamarin.Forms.Maps.Pin aNewPin = new Pin();
                    //aNewPin.Position = new Position(this.customPins[nOdx].Latitude, this.customPins[nOdx].Longitude);
                    //aNewPin.Label = "";
                    ////Control.Children.Add(aPin);
                    //Element.Pins.Add(aNewPin);
                    ////     } else {
                    ////         System.Windows.Media.Color aColorOrange = System.Windows.Media.Color.FromRgb(255, 128, 0);
                    ////         System.Windows.Media.Color aColorWhite = System.Windows.Media.Color.FromRgb(255, 255, 255);
                    ////         MapControl.Pushpin aPin = new MapControl.Pushpin {
                    ////             Location = aLoc,
                    ////             Background = new System.Windows.Media.SolidColorBrush(aColorOrange),
                    ////             Foreground = new System.Windows.Media.SolidColorBrush(aColorWhite)
                    ////         };
                    //////Control.Children.Add(aPin);
                    ////     }
                    //// Microsoft.Maps.MapControl.WPF.Location aLoc = new Microsoft.Maps.MapControl.WPF.Location(pin.Position.Latitude, pin.Position.Longitude); //Convert.ToDouble( _myGeocodeInfo[8]),Convert.ToDouble(_myGeocodeInfo[9]));
                    ////Microsoft.Maps.MapControl.WPF.Pushpin aPin = new Microsoft.Maps.MapControl.WPF.Pushpin();
                    ////Microsoft.Maps.MapControl.WPF.MapLayer.SetPosition(aPin, aLoc);
                    ////         Microsoft.Maps.MapControl.WPF.Location aLoc = new Microsoft.Maps.MapControl.WPF.Location(this.customPins[nOdx].Latitude, this.customPins[nOdx].Longitude);
                    ////         Microsoft.Maps.MapControl.WPF.Pushpin aPin = new Microsoft.Maps.MapControl.WPF.Pushpin();
                    ////         Microsoft.Maps.MapControl.WPF.MapLayer.SetPosition(aPin, aLoc);
                    ////Control.Children.Add(aPin);
                    ////var snPosition = new BasicGeoposition { Latitude = this.customPins[nOdx].Latitude, Longitude = this.customPins[nOdx].Longitude };
                    ////var snPoint = new Geopoint(snPosition);
                    ////var mapIcon = new MapIcon();

                    ////if (this.customPins[nOdx].BluePin) {
                    ////    string sUriString = "ms-appx:///bluemappin50.png";
                    ////    mapIcon.Image = RandomAccessStreamReference.CreateFromUri(new Uri(sUriString));
                    ////} else {
                    ////    string sUriString = "ms-appx:///orangemappin50.png";
                    ////    mapIcon.Image = RandomAccessStreamReference.CreateFromUri(new Uri(sUriString));
                    ////}
                    ////mapIcon.CollisionBehaviorDesired = MapElementCollisionBehavior.RemainVisible;
                    ////mapIcon.Location = snPoint;
                    ////mapIcon.NormalizedAnchorPoint = new Windows.Foundation.Point(0.5, 1.0);

                    ////this.nativeMap.MapElements.Add(mapIcon);
                }
            }
        }
Exemple #33
0
        internal static FrameworkElementFactory CreateBoundCellRenderer(ApplicationContext ctx, WidgetBackend parent, CellView view, string dataPath = ".")
        {
            ICellViewFrontend fr       = view;
            TextCellView      textView = view as TextCellView;

            if (textView != null)
            {
                // if it's an editable textcontrol, use a TextBox, if not use a TextBlock. Reason for this is that
                // a user usually expects to be able to edit a text if a text cursor is appearing above a field.
                FrameworkElementFactory factory;
                if (textView.Editable || textView.EditableField != null)
                {
                    factory = new FrameworkElementFactory(typeof(SWC.TextBox));
                    if (textView.Editable)
                    {
                        factory.SetValue(SWC.TextBox.IsReadOnlyProperty, false);
                    }
                    else
                    {
                        factory.SetBinding(SWC.TextBox.IsEnabledProperty, new Binding(dataPath + "[" + textView.EditableField.Index + "]"));
                    }

                    if (textView.TextField != null)
                    {
                        factory.SetBinding(SWC.TextBox.TextProperty, new Binding(dataPath + "[" + textView.TextField.Index + "]"));
                    }
                    else
                    {
                        factory.SetValue(SWC.TextBox.TextProperty, textView.Text);
                    }
                }
                else
                {
                    factory = new FrameworkElementFactory(typeof(SWC.TextBlock));

                    if (textView.MarkupField != null)
                    {
                        factory.SetBinding(SWC.TextBlock.TextProperty, new Binding(dataPath + "[" + textView.MarkupField.Index + "]")
                        {
                            Converter = new MarkupToPlainTextConverter()
                        });
                    }
                    else if (textView.TextField != null)
                    {
                        factory.SetBinding(SWC.TextBlock.TextProperty, new Binding(dataPath + "[" + textView.TextField.Index + "]"));
                    }
                    else
                    {
                        factory.SetValue(SWC.TextBlock.TextProperty, textView.Text);
                    }
                }

                var cb = new TextCellViewBackend();
                cb.Initialize(view, factory, parent as ICellRendererTarget);
                fr.AttachBackend(parent.Frontend, cb);
                return(factory);
            }

            ImageCellView imageView = view as ImageCellView;

            if (imageView != null)
            {
                FrameworkElementFactory factory = new FrameworkElementFactory(typeof(ImageBox));

                if (imageView.ImageField != null)
                {
                    var binding = new Binding(dataPath + "[" + imageView.ImageField.Index + "]");
                    binding.Converter = new ImageToImageSourceConverter(ctx);

                    factory.SetBinding(ImageBox.ImageSourceProperty, binding);
                }

                var cb = new CellViewBackend();
                cb.Initialize(view, factory, parent as ICellRendererTarget);
                fr.AttachBackend(parent.Frontend, cb);
                return(factory);
            }

            CanvasCellView canvasView = view as CanvasCellView;

            if (canvasView != null)
            {
                var cb = new CanvasCellViewBackend();
                FrameworkElementFactory factory = new FrameworkElementFactory(typeof(CanvasCellViewPanel));
                factory.SetValue(CanvasCellViewPanel.CellViewBackendProperty, cb);

                cb.Initialize(view, factory, parent as ICellRendererTarget);
                fr.AttachBackend(parent.Frontend, cb);
                return(factory);
            }

            CheckBoxCellView cellView = view as CheckBoxCellView;

            if (cellView != null)
            {
                FrameworkElementFactory factory = new FrameworkElementFactory(typeof(CheckBoxCell));
                if (cellView.EditableField == null)
                {
                    factory.SetValue(FrameworkElement.IsEnabledProperty, cellView.Editable);
                }
                else
                {
                    factory.SetBinding(SWC.CheckBox.IsEnabledProperty, new Binding(dataPath + "[" + cellView.EditableField.Index + "]"));
                }

                if (cellView.AllowMixedField == null)
                {
                    factory.SetValue(SWC.CheckBox.IsThreeStateProperty, cellView.AllowMixed);
                }
                else
                {
                    factory.SetBinding(SWC.CheckBox.IsThreeStateProperty, new Binding(dataPath + "[" + cellView.AllowMixedField.Index + "]"));
                }

                if (cellView.StateField != null)
                {
                    factory.SetBinding(SWC.CheckBox.IsCheckedProperty,
                                       new Binding(dataPath + "[" + cellView.StateField.Index + "]")
                    {
                        Converter = new CheckBoxStateToBoolConverter()
                    });
                }
                else if (cellView.ActiveField != null)
                {
                    factory.SetBinding(SWC.CheckBox.IsCheckedProperty, new Binding(dataPath + "[" + cellView.ActiveField.Index + "]"));
                }

                var cb = new CheckBoxCellViewBackend();
                cb.Initialize(view, factory, parent as ICellRendererTarget);
                fr.AttachBackend(parent.Frontend, cb);
                return(factory);
            }

            var radioButton = view as RadioButtonCellView;

            if (radioButton != null)
            {
                FrameworkElementFactory factory = new FrameworkElementFactory(typeof(UngroupedRadioButton));
                if (radioButton.EditableField == null)
                {
                    factory.SetValue(UIElement.IsEnabledProperty, radioButton.Editable);
                }
                else
                {
                    factory.SetBinding(UIElement.IsEnabledProperty, new Binding(dataPath + "[" + radioButton.EditableField.Index + "]"));
                }

                factory.SetValue(SWC.Primitives.ToggleButton.IsThreeStateProperty, false);
                if (radioButton.ActiveField == null)
                {
                    factory.SetValue(SWC.Primitives.ToggleButton.IsCheckedProperty, radioButton.Active);
                }
                else
                {
                    factory.SetBinding(SWC.Primitives.ToggleButton.IsCheckedProperty, new Binding(dataPath + "[" + radioButton.ActiveField.Index + "]"));
                }

                var cb = new RadioButtonCellViewBackend();
                cb.Initialize(view, factory, parent as ICellRendererTarget);
                fr.AttachBackend(parent.Frontend, cb);
                return(factory);
            }

            throw new NotImplementedException();
        }
Exemple #34
0
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            var tp = Template.FindName("PART_HeaderPanel", this) as ScrollablePanel;

            if (tp != null)
            {
                tp.SetBinding(ScrollablePanel.SelectedItemProperty, new Binding(SelectedItemProperty.Name)
                {
                    Mode = BindingMode.TwoWay, Source = this
                });
                tp.SetBinding(ScrollablePanel.ScrollToLeftContentProperty, new Binding(ScrollToLeftContentProperty.Name)
                {
                    Mode = BindingMode.TwoWay, Source = this
                });
                tp.SetBinding(ScrollablePanel.ScrollToRightContentProperty, new Binding(ScrollToRightContentProperty.Name)
                {
                    Mode = BindingMode.TwoWay, Source = this
                });
                tp.SetBinding(ScrollablePanel.SelectItemOnScrollProperty, new Binding(SelectItemOnScrollProperty.Name)
                {
                    Mode = BindingMode.TwoWay, Source = this
                });
            }
            var sb = Template.FindName("PART_QuickLinksHost", this) as MenuButton;

            if (sb != null)
            {
                if (tp != null)
                {
                    var b = new MultiBinding()
                    {
                        Converter = new BoolToVisibilityConverter()
                    };
                    b.Bindings.Add(new Binding(ScrollablePanel.IsTruncatingItemsProperty.Name)
                    {
                        Source = tp, Mode = BindingMode.OneWay
                    });
                    b.Bindings.Add(new Binding(TabControl.ShowQuickLinksButtonProperty.Name)
                    {
                        Source = this, Mode = BindingMode.OneWay
                    });
                    sb.SetBinding(UIElement.VisibilityProperty, b);
                }
                sb.SetBinding(ItemsControl.ItemsSourceProperty, new Binding("Items")
                {
                    Mode = BindingMode.OneWay, Source = this
                });
                sb.SetBinding(MenuButton.CommandProperty, new Binding(NavigateToItemCommandProperty.Name)
                {
                    Mode = BindingMode.OneWay, Source = this
                });
                if (sb.ItemTemplate == null && sb.GetBindingExpression(ItemsControl.ItemTemplateProperty) == null)
                {
                    var factory = new FrameworkElementFactory(typeof(ContentPresenter));
                    factory.SetValue(FrameworkElement.HorizontalAlignmentProperty, HorizontalAlignment.Left);
                    factory.SetBinding(ContentPresenter.ContentProperty, new Binding()
                    {
                        Converter = new WrapVisualConverter(), ConverterParameter = this
                    });
                    factory.SetBinding(ContentPresenter.ContentTemplateProperty, new Binding(ItemTemplateProperty.Name)
                    {
                        Source = this
                    });
                    sb.ItemTemplate = new DataTemplate()
                    {
                        VisualTree = factory
                    };
                }
            }
        }
Exemple #35
0
        private void Build(String text, String arrayText, String dataGridName)
        {
            Console.WriteLine("arrayText " + arrayText);
            StackPanel spMain = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                Margin      = new Thickness(20, 10, 0, 0)
            };
            TextBlock lblText = new TextBlock
            {
                VerticalAlignment = VerticalAlignment.Center,
                Margin            = new Thickness(0, 30, 10, 0),
                Text = text
            };
            TextBox tbText = new TextBox
            {
                Name  = "txt_" + dataGridName,
                Width = 300,
                HorizontalAlignment = HorizontalAlignment.Left,
                BorderBrush         = Brushes.White,
                BorderThickness     = new Thickness(1),
                Background          = Brushes.LightGray,
                Foreground          = Brushes.Black,
                Margin = new Thickness(0, 0, 10, 0),
            };
            Button btnAdd = new Button
            {
                Name                = "btn_" + dataGridName,
                Content             = "追加",
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment   = VerticalAlignment.Center,
                Tag = dataGridName,
            };

            btnAdd.AddHandler(Button.ClickEvent, new RoutedEventHandler(btnAdd_Click));
            StackPanel spChild = new StackPanel
            {
                Orientation         = Orientation.Horizontal,
                Margin              = new Thickness(0, 0, 0, 10),
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment   = VerticalAlignment.Center
            };

            spChild.Children.Add(tbText);
            spChild.Children.Add(btnAdd);
            dataGrid = new DataGrid
            {
                Name                = dataGridName,
                BorderBrush         = Brushes.Green,
                BorderThickness     = new Thickness(1),
                HorizontalAlignment = HorizontalAlignment.Left,
                MaxHeight           = 300,
                CanUserAddRows      = false,
                AutoGenerateColumns = false
            };
            DataGridTextColumn col1 = new DataGridTextColumn();
            var ab = arrayText.Trim().Split(',');

            for (int i = 0; i < ab.Length; i++)
            {
                dataGrid.Items.Add(new Data()
                {
                    Value = ab[i]
                });
            }
            col1.Header  = "Value";
            col1.Binding = new Binding("Value");
            dataGrid.Columns.Add(col1);

            DataGridTemplateColumn col = new DataGridTemplateColumn();

            col.Header = "削除";
            DataTemplate dt = new DataTemplate();
            var          sp = new FrameworkElementFactory(typeof(StackPanel));

            sp.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);

            var btnDelete = new FrameworkElementFactory(typeof(Button));

            btnDelete.SetValue(Button.TagProperty, dataGridName);
            btnDelete.SetValue(Button.ContentProperty, "削除");
            btnDelete.AddHandler(Button.ClickEvent, new RoutedEventHandler(btnDelete_Click));
            btnDelete.SetValue(Button.MarginProperty, new Thickness(0, 0, 10, 0));
            sp.AppendChild(btnDelete);

            dt.VisualTree    = sp;
            col.CellTemplate = dt;
            dataGrid.Columns.Add(col);
            spSettings.Children.Add(lblText);
            spSettings.Children.Add(spChild);
            spSettings.Children.Add(dataGrid);
        }
Exemple #36
0
        private void cmbOdeljenje_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbOdeljenje.SelectedIndex != -1)
            {
                for (int i = 0; i < trenutniPredmeti.Count; i++)
                {
                    ((GridView)lvv.View).Columns.RemoveAt(1);
                }

                int raz = Convert.ToInt32(cmbRazred.SelectedValue);
                int ode = Convert.ToInt32(cmbOdeljenje.SelectedValue);
                trenutniUcenici  = Ucenik.Daj().Where(u => u.razred == raz && u.odeljenje == ode).ToList();
                cursmer          = trenutniUcenici[0].smer;
                lbSmer.Content   = cursmer.naziv;
                trenutniPredmeti = Smer.DajPredmete(cursmer, raz).ToList();

                DataTable sors = new DataTable();
                sors.Columns.Add("ime", typeof(string));

                foreach (Predmet pr in trenutniPredmeti)
                {
                    string x = pr.naziv.Trim().Replace(".", "");
                    sors.Columns.Add(x, typeof(string));

                    GridViewColumn col = new GridViewColumn();
                    col.Header = pr.naziv;

                    DataTemplate temp = new DataTemplate();

                    FrameworkElementFactory bor = new FrameworkElementFactory(typeof(Border));
                    bor.SetValue(Border.BorderBrushProperty, Brushes.LightGray);
                    bor.SetValue(Border.BorderThicknessProperty, new Thickness(0, 0, 1, 1));
                    bor.SetValue(Border.MarginProperty, new Thickness(-6, 0, -6, 0));

                    RoutedEventHandler izgubioFokus = Fokus;
                    RoutedEventHandler dobioFokus   = DFokus;

                    FrameworkElementFactory title = new FrameworkElementFactory(typeof(TextBox));
                    title.SetValue(TextBox.FontWeightProperty, FontWeights.Bold);
                    title.SetBinding(TextBox.TextProperty, new Binding(x));
                    title.SetValue(TextBox.MarginProperty, new Thickness(5));
                    title.AddHandler(TextBox.LostFocusEvent, izgubioFokus);
                    title.AddHandler(TextBox.GotFocusEvent, dobioFokus);
                    title.SetValue(TextBox.WidthProperty, (double)23);
                    title.SetValue(TextBox.TabIndexProperty, 1);
                    title.SetValue(TextBox.IsTabStopProperty, true);

                    bor.AppendChild(title);
                    temp.VisualTree  = bor;
                    col.CellTemplate = temp;

                    ((GridView)lvv.View).Columns.Add(col);
                }

                foreach (Ucenik uc in trenutniUcenici)
                {
                    DataRow row = sors.NewRow();
                    row[0] = uc.naziv;
                    int i = 1;
                    foreach (Predmet pr in trenutniPredmeti)
                    {
                        int?ocena = Ucenik.OcenaIz((int)uc.broj, pr.id, App.Godina());;
                        if (ocena == null)
                        {
                            row[i] = "";
                        }
                        else
                        {
                            row[i] = ocena.ToString();
                        }
                        i++;
                    }
                    sors.Rows.Add(row);
                }

                trenutniSors    = sors.Copy();
                lvv.ItemsSource = sors.DefaultView;
                ((GridView)lvv.View).Columns[0].Width = 200;
            }
        }