Inheritance: System.Windows.TriggerBase, System.Windows.Markup.IAddChild
コード例 #1
2
 // This block of code attempts to minimize the number of
 //  type operations and assignments involved in figuring out what
 //  trigger type we're dealing here.
 // Attempted casts are done in the order of decreasing expected frequency.
 //  rearrange as expectations change.
 private static void DetermineTriggerType( TriggerBase triggerBase,
     out Trigger trigger, out MultiTrigger multiTrigger,
     out DataTrigger dataTrigger, out MultiDataTrigger multiDataTrigger,
     out EventTrigger eventTrigger )
 {
     if( (trigger = (triggerBase as Trigger)) != null )
     {
         multiTrigger = null;
         dataTrigger = null;
         multiDataTrigger = null;
         eventTrigger = null;
     }
     else if( (multiTrigger = (triggerBase as MultiTrigger)) != null )
     {
         dataTrigger = null;
         multiDataTrigger = null;
         eventTrigger = null;
     }
     else if( (dataTrigger = (triggerBase as DataTrigger)) != null )
     {
         multiDataTrigger = null;
         eventTrigger = null;
     }
     else if( (multiDataTrigger = (triggerBase as MultiDataTrigger)) != null )
     {
         eventTrigger = null;
     }
     else if( (eventTrigger = (triggerBase as EventTrigger)) != null )
     {
         ; // Do nothing - eventTrigger is now non-null, and everything else has been set to null.
     }
     else
     {
         // None of the above - the caller is expected to throw an exception
         //  stating that the trigger type is not supported.
     }
 }
コード例 #2
2
ファイル: GridHelper.cs プロジェクト: T1Easyware/Soheil
		private static void SetAllColumns(Grid grid)
		{
			grid.ColumnDefinitions.Clear();

			var pgList = GetAllColumns(grid);
			foreach (var productgroup in pgList)
			{
				var cd = new ColumnDefinition();
				cd.Width = new GridLength(ProductGroup.HeaderColumnWidth, GridUnitType.Pixel);
				grid.ColumnDefinitions.Add(cd);
				foreach (var product in productgroup.Products)
				{
					foreach (var rework in product.Reworks)
					{
						cd = new ColumnDefinition();
						cd.DataContext = rework;

						var style = new Style(typeof(ColumnDefinition));
						style.Setters.Add(new Setter(
							ColumnDefinition.WidthProperty,
							new GridLength(ProductGroup.ColumnWidth, GridUnitType.Pixel)));

						#region open animation
						var animation = new GridLengthAnimation();
						animation.From = new GridLength(0, GridUnitType.Pixel);
						animation.To = new GridLength(ProductGroup.ColumnWidth, GridUnitType.Pixel);
						animation.Duration = TimeSpan.FromSeconds(0.2);
						Storyboard.SetTargetProperty(animation, new PropertyPath("Width"));

						var storyboard = new Storyboard();
						storyboard.Children.Add(animation);
						#endregion

						#region close animation
						var animation2 = new GridLengthAnimation();
						animation2.From = new GridLength(ProductGroup.ColumnWidth, GridUnitType.Pixel);
						animation2.To = new GridLength(0, GridUnitType.Pixel);
						animation2.Duration = TimeSpan.FromSeconds(0.2);
						Storyboard.SetTargetProperty(animation2, new PropertyPath("Width"));

						var storyboard2 = new Storyboard();
						storyboard2.Children.Add(animation2);
						#endregion

						if (rework.IsRework)
						{
							var multitrigger = new MultiDataTrigger();
							multitrigger.Conditions.Add(new Condition(new Binding("Product.IsExpanded"), true));
							multitrigger.Conditions.Add(new Condition(new Binding("Product.ProductGroup.IsExpanded"), true));
							multitrigger.EnterActions.Add(new BeginStoryboard { Storyboard = storyboard });
							multitrigger.ExitActions.Add(new BeginStoryboard { Storyboard = storyboard2 });
							style.Triggers.Add(multitrigger);
						}
						else
						{
							var trigger = new DataTrigger();
							trigger.Binding = new Binding("Product.ProductGroup.IsExpanded");
							trigger.Value = true;
							trigger.EnterActions.Add(new BeginStoryboard { Storyboard = storyboard });
							trigger.ExitActions.Add(new BeginStoryboard { Storyboard = storyboard2 });
							style.Triggers.Add(trigger);
						}

						cd.Style = style;
						grid.ColumnDefinitions.Add(cd);
					}

				}
			}
			grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
		}
コード例 #3
2
        private static TriggerBase CreateTrigger(EntityFieldInfo fieldInfo, IDataService dataService, GenericDataListState state, Nullable<Boolean> isLocked, FrameworkElement element)
        {
            TriggerBase trigger = null;
            if (isLocked.HasValue)
            {
                MultiDataTrigger multiDataTrigger = new MultiDataTrigger();
                Condition conditionState = new Condition();
                conditionState.Binding = CreateBindingState(element);
                conditionState.Value = state;
                multiDataTrigger.Conditions.Add(conditionState);
                Condition conditionIsLocked = new Condition();
                conditionIsLocked.Binding = CreateBindingIsLocked(element);
                conditionIsLocked.Value = isLocked.Value;
                multiDataTrigger.Conditions.Add(conditionIsLocked);
                multiDataTrigger.Setters.Add(DataControlTemplateBuilder.CreateSetter(fieldInfo, dataService, state, isLocked, element));
                trigger = multiDataTrigger;
            }
            else
            {
                DataTrigger dataTrigger = new DataTrigger();
                dataTrigger.Binding = DataControlTemplateBuilder.CreateBindingState(element);
                dataTrigger.Value = state;
                dataTrigger.Setters.Add(DataControlTemplateBuilder.CreateSetter(fieldInfo, dataService, state, isLocked, element));
                trigger = dataTrigger;
            }

            return trigger;
        }
コード例 #4
0
ファイル: ComboBoxBackend.cs プロジェクト: steffenWi/xwt
        //private static readonly DataTemplate DefaultTemplate;
        static ComboBoxBackend()
        {
            if (System.Windows.Application.Current.Resources.MergedDictionaries.Count == 0 ||
                !System.Windows.Application.Current.Resources.MergedDictionaries.Any(x => x.Contains(typeof(ExComboBox))))
            {
                var factory = new FrameworkElementFactory(typeof(WindowsSeparator));
                factory.SetValue(FrameworkElement.HorizontalAlignmentProperty, HorizontalAlignment.Stretch);

                var sepTemplate = new ControlTemplate(typeof(ComboBoxItem));
                sepTemplate.VisualTree = factory;

                DataTrigger trigger = new DataTrigger();
                trigger.Binding = new Binding(".[1]") { Converter = new TypeToStringConverter() };
                trigger.Value = typeof(ItemSeparator).Name;
                trigger.Setters.Add(new Setter(Control.TemplateProperty, sepTemplate));
                trigger.Setters.Add(new Setter(UIElement.IsEnabledProperty, false));

                ContainerStyle = new Style(typeof(ComboBoxItem));
                ContainerStyle.Triggers.Add(trigger);
            }
            else
            {
                ContainerStyle = null;
            }
        }
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            var row = item as ContradictionViewModel;
            if (row == null)
                return null;

            IEnumerable<DependencyObject> cellPanelRoute = TreeHelper.GetRouteToAncestor<DataGridCellsPanel>(container);
            if (cellPanelRoute.Count() < 2)
                return null;

            DataGridCellsPanel cellPanel = cellPanelRoute.ElementAt(0) as DataGridCellsPanel;
            DataGridCell currentCell = cellPanelRoute.ElementAt(1) as DataGridCell;
            //First item is the header, so minus 1
            int ruleIndex = cellPanel.Children.IndexOf(currentCell) - 1;

            //Build common background border
            //selected rows and columns will be highlighted
            var borderStyle = new Style { TargetType = typeof(Border) };
            var highlightBrush = new SolidColorBrush(Color.FromArgb(0xE0, 0xC6, 0xD3, 0xD3));
            var isSelectedTriggerOne = new DataTrigger
            {
                Binding = new Binding("Header.IsSelected"),
                Value = true
            };
            isSelectedTriggerOne.Setters.Add(new Setter(Border.BackgroundProperty, highlightBrush));

            var isSelectedTriggerTwo = new DataTrigger
            {
                Binding = new Binding(string.Format("Rules[{0}].IsSelected", ruleIndex)),
                Value = true
            };
            isSelectedTriggerTwo.Setters.Add(new Setter(Border.BackgroundProperty, highlightBrush));

            borderStyle.Triggers.Add(isSelectedTriggerOne);
            borderStyle.Triggers.Add(isSelectedTriggerTwo);

            FrameworkElementFactory borderFactory = new FrameworkElementFactory(typeof(Border));
            borderFactory.SetValue(Border.StyleProperty, borderStyle);

            //since this is readonly and the states won't change, there's no binding required here.
            //just decide what properties to use right here.
            bool? isContradicted = row.ContradictionStates[ruleIndex];
            if (isContradicted == null)
            {
                borderFactory.SetValue(Border.BackgroundProperty, Brushes.LightGray);
            }
            else if (isContradicted == true)
            {
                FrameworkElementFactory textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
                textBlockFactory.SetValue(TextBlock.TextProperty, "X");
                textBlockFactory.SetValue(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Center);
                textBlockFactory.SetValue(TextBlock.VerticalAlignmentProperty, VerticalAlignment.Center);

                borderFactory.AppendChild(textBlockFactory);
            }

            return new DataTemplate { VisualTree = borderFactory };
        }
コード例 #6
0
        private Style CreateStyle()
        {
            var style = new Style();

            var trigger = new DataTrigger();
            trigger.Binding = new Binding("Cty"); //misspelling
            trigger.Value = "Tallahassee";

            style.Triggers.Add(trigger);

            return style;
        }
コード例 #7
0
        private DataTemplate CreateItemTemplate()
        {
            var template = new DataTemplate();

            template.VisualTree = new FrameworkElementFactory(typeof(StackPanel));

            var trigger = new DataTrigger();
            trigger.Binding = new Binding("Cty"); //misspelling
            trigger.Value = "Tallahassee";

            template.Triggers.Add(trigger);

            return template;
        }
コード例 #8
0
        public ActionsAndVersions()
        {
            InitializeComponent();

            // Change ItemContainerStyle of the _versions combobox so that 
            // for a null value, a separator is generated.
            var dataTrigger = new DataTrigger();
            dataTrigger.Binding = new Binding();
            dataTrigger.Value = null;
            dataTrigger.Setters.Add(new Setter(ComboBoxItem.TemplateProperty, this.FindResource("SeparatorControlTemplate")));

            var style = new Style(typeof(ComboBoxItem), _versions.ItemContainerStyle);
            style.Triggers.Add(dataTrigger);
            _versions.ItemContainerStyle = style;
        }
コード例 #9
0
        private Style CreateStyle()
        {
            var style = new Style();

            var multibinding = new MultiBinding { Converter = new SimpleMultiValueConverter() };
            multibinding.Bindings.Add(new Binding("FirstName"));
            multibinding.Bindings.Add(new Binding("LstName")); //purposefully misspelled

            var trigger = new DataTrigger();
            trigger.Binding = multibinding;
            trigger.Value = "Rob Eisenberg";

            style.Triggers.Add(trigger);

            return style;
        }
コード例 #10
0
ファイル: ComboBoxBackend.cs プロジェクト: jfreax/xwt
        //private static readonly DataTemplate DefaultTemplate;
        static ComboBoxBackend()
        {
            var factory = new FrameworkElementFactory (typeof (WindowsSeparator));
            factory.SetValue (FrameworkElement.HorizontalAlignmentProperty, HorizontalAlignment.Stretch);

            var sepTemplate = new ControlTemplate (typeof (ComboBoxItem));
            sepTemplate.VisualTree = factory;

            DataTrigger trigger = new DataTrigger();
            trigger.Binding = new Binding (".[1]") { Converter = new TypeToStringConverter() };
            trigger.Value = typeof(ItemSeparator).Name;
            trigger.Setters.Add (new Setter (Control.TemplateProperty, sepTemplate));
            trigger.Setters.Add (new Setter (UIElement.IsEnabledProperty, false));

            ContainerStyle = new Style (typeof (ComboBoxItem));
            ContainerStyle.Triggers.Add (trigger);
        }
コード例 #11
0
        private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            var textColumn = e.Column as DataGridTextColumn;
            if (textColumn == null) return;
            textColumn.Width = new DataGridLength(200, DataGridLengthUnitType.Pixel);

            var style = new Style(typeof(DataGridCell));
            textColumn.CellStyle = style;

            if (textColumn.Header.ToString() == "Key")
                ((Binding)textColumn.Binding).ValidationRules.Add(new IsNullOrWhiteSpaceValidationRule());

            var emptyStringTrigger = new DataTrigger { Binding = textColumn.Binding };
            emptyStringTrigger.Value = string.Empty;
            emptyStringTrigger.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Color.FromRgb(255, 255, 153))));
            style.Triggers.Add(emptyStringTrigger);
        }
コード例 #12
0
        /// <summary>Handles cases where a markup extension provides a value for a property of a <see cref="T:System.Windows.DataTrigger" /> object.</summary>
        /// <param name="targetObject">The object where the markup extension sets the value.</param>
        /// <param name="eventArgs">Data that is relevant for markup extension processing.</param>
        // Token: 0x0600039A RID: 922 RVA: 0x0000A564 File Offset: 0x00008764
        public static void ReceiveMarkupExtension(object targetObject, XamlSetMarkupExtensionEventArgs eventArgs)
        {
            if (targetObject == null)
            {
                throw new ArgumentNullException("targetObject");
            }
            if (eventArgs == null)
            {
                throw new ArgumentNullException("eventArgs");
            }
            DataTrigger dataTrigger = targetObject as DataTrigger;

            if (dataTrigger != null && eventArgs.Member.Name == "Binding" && eventArgs.MarkupExtension is BindingBase)
            {
                dataTrigger.Binding = (eventArgs.MarkupExtension as BindingBase);
                eventArgs.Handled   = true;
                return;
            }
            eventArgs.CallBase();
        }
コード例 #13
0
ファイル: TriggerTest.cs プロジェクト: highzion/Granular
        public void DataTriggerBasicTest()
        {
            DataTrigger trigger = new DataTrigger { Binding = new Binding(), Value = 1 };
            trigger.Setters.Add(new Setter { Property = new DependencyPropertyPathElement(Value1Property), Value = 1 });

            FrameworkElement element = new FrameworkElement();
            element.DataContext = 1;
            Assert.AreEqual(0, element.GetValue(Value1Property));

            element.Triggers.Add(trigger);
            Assert.AreEqual(1, element.GetValue(Value1Property));

            element.DataContext = 2;
            Assert.AreEqual(0, element.GetValue(Value1Property));

            element.DataContext = 1;
            Assert.AreEqual(1, element.GetValue(Value1Property));

            element.Triggers.Remove(trigger);
            Assert.AreEqual(0, element.GetValue(Value1Property));
        }
        private DataTemplate CreateItemTemplate()
        {
            var template = new DataTemplate();

            template.VisualTree = new FrameworkElementFactory(typeof(StackPanel));

            var txtBlock = new FrameworkElementFactory(typeof(TextBlock));
            txtBlock.SetBinding(TextBlock.TextProperty, new Binding("Street1")); 
            template.VisualTree.AppendChild(txtBlock);

            txtBlock = new FrameworkElementFactory(typeof(TextBlock));
            txtBlock.SetBinding(TextBlock.TextProperty, new Binding("City")); 
            template.VisualTree.AppendChild(txtBlock);

            var trigger = new DataTrigger();
            trigger.Binding = new Binding("Cty"); //misspelling
            trigger.Value = "Tallahassee";

            template.Triggers.Add(trigger);

            return template;
        }
コード例 #15
0
        private void NullableComboBox_Loaded(object sender, RoutedEventArgs e)
        {
            // Combo boxes can be annoying with null selection when using a collection view for the ItemsSource (since
            // ICollectionView cannot be composited out of the box), so this is the smallest workaround to get the 
            // desired behavior.

            ComboBox comboBox = sender as ComboBox;
            if ((comboBox != null) && !(comboBox.Tag is bool))
            {
#if DEBUG
                comboBox.KeyDown += NullableComboBox_KeyDown;
#endif // DEBUG

                string path = comboBox.Tag as string;
                if (path != null)
                {
                    Binding selectedItemBinding = new Binding(path);
                    comboBox.SetBinding(ComboBox.SelectedItemProperty, selectedItemBinding);

                    DataTrigger selectedItemDataTrigger = new DataTrigger()
                        { 
                            Binding = selectedItemBinding,
                        };

                    Setter selectedIndexSetter = new Setter(ComboBox.SelectedIndexProperty, -1);
                    selectedItemDataTrigger.Setters.Add(selectedIndexSetter);
                }


                comboBox.Tag = true;
            }
        }
コード例 #16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DataTriggerItem"/> class.
 /// </summary>
 public DataTriggerItem(DataTrigger trigger, FrameworkElement source, TriggerSource triggerSource)
     : base(source, TriggerType.DataTrigger, triggerSource)
 {
     _dataTrigger = trigger;
     _source = source;
 }
コード例 #17
0
        private static DataTrigger CreateTrigger(EntityFieldInfo entityFieldInfo, GenericDataListState state, DataGrid dataGrid)
        {
            DataTrigger dataTrigger = new DataTrigger();
              dataTrigger.Binding = CreateBindingState(state, dataGrid);
              dataTrigger.Value = state;
              dataTrigger.Setters.Add(CreateSetter(entityFieldInfo, state, dataGrid));

              return dataTrigger;
        }
コード例 #18
0
ファイル: Chart.xaml.cs プロジェクト: xyandro/NeoEdit
		public void RecalculatePieChart()
		{
			if (data.Count < 2)
				return;

			pieChart.Children.Clear();

			var radius = Math.Min(pieChart.ActualWidth, pieChart.ActualHeight) / 2;
			if (radius <= 0)
				return;
			var center = new Point(radius, radius);

			double start = 0;
			var total = data.Sum(num => num.Item3);
			for (var ctr = 0; ctr < data.Count; ++ctr)
			{
				var item = data[ctr];
				var key = legend.Children[ctr] as FrameworkElement;
				var brush = brushes[ctr];

				var end = start + (double)item.Item3 / total * 2 * Math.PI;
				var arc = GetArc(center, radius, start, end, brush, item.Item1, item.Item3);
				start = end;
				pieChart.Children.Add(arc);

				var style = new Style();
				style.Setters.Add(new Setter { Property = Path.RenderTransformProperty, Value = null });
				var trigger = new DataTrigger { Binding = new Binding("IsMouseOver") { Source = arc }, Value = true };
				trigger.Setters.Add(new Setter { Property = Path.RenderTransformProperty, Value = new ScaleTransform(1.05, 1.05, center.X, center.Y) });
				style.Triggers.Add(trigger);
				trigger = new DataTrigger { Binding = new Binding("IsMouseOver") { Source = key }, Value = true };
				trigger.Setters.Add(new Setter { Property = Path.RenderTransformProperty, Value = new ScaleTransform(1.05, 1.05, center.X, center.Y) });
				style.Triggers.Add(trigger);
				arc.Style = style;

				style = new Style();
				style.Setters.Add(new Setter { Property = Canvas.BackgroundProperty, Value = null });
				trigger = new DataTrigger { Binding = new Binding("IsMouseOver") { Source = arc }, Value = true };
				trigger.Setters.Add(new Setter { Property = Canvas.BackgroundProperty, Value = Brushes.LightGray });
				style.Triggers.Add(trigger);
				trigger = new DataTrigger { Binding = new Binding("IsMouseOver") { Source = key }, Value = true };
				trigger.Setters.Add(new Setter { Property = Canvas.BackgroundProperty, Value = Brushes.LightGray });
				style.Triggers.Add(trigger);
				key.Style = style;
			}
		}
コード例 #19
0
ファイル: WowProtocol.cs プロジェクト: CarlosX/Kamilla.Wow
        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);
            }
        }
コード例 #20
0
        public override DependencyObject CreateTrigger(StyleSheet styleSheet, ITrigger trigger, Type targetType, DependencyObject styleResourceReferenceHolder)
        {
            if (trigger == null)
            {
                throw new ArgumentNullException(nameof(trigger));
            }

            if (trigger is Trigger)
            {
                var propertyTrigger = trigger as Trigger;
                var nativeTrigger   = new System.Windows.Trigger();

                var dependencyProperty = dependencyService.GetBindableProperty(targetType, propertyTrigger.Property);
                if (dependencyProperty == null)
                {
                    throw new NullReferenceException($"Property '{propertyTrigger.Property}' may not be null (targetType '{targetType.Name}')!");
                }

                nativeTrigger.Property = dependencyProperty;
                nativeTrigger.Value    = dependencyService.GetBindablePropertyValue(targetType, nativeTrigger.Property, propertyTrigger.Value);

                foreach (var styleDeclaration in propertyTrigger.StyleDeclaraionBlock)
                {
                    var property = typeNameResolver.GetDependencyProperty(styleSheet.Namespaces, targetType, styleDeclaration.Property);
                    if (property == null)
                    {
                        continue;
                    }
                    var value = typeNameResolver.GetPropertyValue(targetType, styleResourceReferenceHolder, styleDeclaration.Value, property);

                    if (value is string valueString)
                    {
                        value = TypeDescriptor.GetConverter(property.PropertyType)?.ConvertFromInvariantString(valueString) ?? value;
                    }

                    nativeTrigger.Setters.Add(new Setter {
                        Property = property, Value = value
                    });
                }

                return(nativeTrigger);
            }
            else if (trigger is DataTrigger)
            {
                var dataTrigger   = trigger as DataTrigger;
                var nativeTrigger = new System.Windows.DataTrigger();

                var expression = "{Binding " + dataTrigger.Binding + "}";

                var binding = (System.Windows.Data.BindingBase)markupExtensionParser.ProvideValue(expression, null);
                nativeTrigger.Binding = binding;

                nativeTrigger.Value = GetBasicValue(dataTrigger);

                foreach (var styleDeclaration in dataTrigger.StyleDeclarationBlock)
                {
                    var property = typeNameResolver.GetDependencyProperty(styleSheet.Namespaces, targetType, styleDeclaration.Property);
                    if (property == null)
                    {
                        continue;
                    }

                    var value = typeNameResolver.GetPropertyValue(targetType, styleResourceReferenceHolder, styleDeclaration.Value, property);

                    if (value is string valueString)
                    {
                        value = TypeDescriptor.GetConverter(property.PropertyType)?.ConvertFromInvariantString(valueString) ?? value;
                    }

                    nativeTrigger.Setters.Add(new Setter {
                        Property = property, Value = value
                    });
                }

                return(nativeTrigger);
            }
            else if (trigger is EventTrigger)
            {
                var eventTrigger  = trigger as EventTrigger;
                var nativeTrigger = new System.Windows.EventTrigger();

                var fieldInfo = targetType.GetField(eventTrigger.Event + "Event", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);

                nativeTrigger.RoutedEvent = (RoutedEvent)fieldInfo.GetValue(null);

                foreach (var action in eventTrigger.Actions)
                {
                    var actionTypeName = typeNameResolver.ResolveFullTypeName(styleSheet.Namespaces, action.Action);
                    var actionType     = Type.GetType(actionTypeName);
                    var triggerAction  = (System.Windows.TriggerAction)Activator.CreateInstance(actionType);

                    var parameters = action.Parameters.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                     .Select(x => x.Trim())
                                     .ToList();

                    foreach (var parameter in parameters)
                    {
                        var                parameterName            = parameter.Split(' ')[0];
                        object             value                    = null;
                        var                parameterValueExpression = parameter.Substring(parameterName.Length + 1).Trim();
                        DependencyProperty depProp;
                        var                type = typeNameResolver.GetClrPropertyType(styleSheet.Namespaces, triggerAction, parameterName);

                        if (typeNameResolver.IsMarkupExtension(parameterValueExpression))
                        {
                            value = typeNameResolver.GetMarkupExtensionValue(styleResourceReferenceHolder, parameterValueExpression);
                        }
                        else if ((depProp = typeNameResolver.GetDependencyProperty(styleSheet.Namespaces, actionType, parameterName)) != null)
                        {
                            value = typeNameResolver.GetPropertyValue(actionType, styleResourceReferenceHolder, parameterValueExpression, depProp);

                            if (value is DynamicResourceExtension)
                            {
                                var dyn             = value as DynamicResourceExtension;
                                var serviceProvider = (IServiceProvider)typeof(Application).GetProperty("ServiceProvider", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(Application.Current);
                                value = dyn.ProvideValue(serviceProvider);
                            }
                            else if (value is StaticResourceExtension)
                            {
                                var dyn             = value as StaticResourceExtension;
                                var serviceProvider = (IServiceProvider)typeof(Application).GetProperty("ServiceProvider", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(Application.Current);
                                value = dyn.ProvideValue(serviceProvider);
                            }
                        }
                        else
                        {
                            value = parameterValueExpression;
                        }

                        if (value is string valueString)
                        {
                            value = TypeDescriptor.GetConverter(type)?.ConvertFromInvariantString(valueString) ?? value;
                        }

                        triggerAction.GetType().GetRuntimeProperty(parameterName).SetValue(triggerAction, value);
                    }

                    nativeTrigger.Actions.Add(triggerAction);
                }

                return(nativeTrigger);
            }

            throw new NotSupportedException($"Trigger '{trigger.GetType().FullName}' is not supported!");
        }
コード例 #21
0
        /// <summary>
        /// Initializes a new instance of the HighlightingSelector class.
        /// </summary>
        public HighlightingSelector()
        {
            var oldState = ServiceLocator.Instance.ReportErrors;
            ServiceLocator.Instance.ReportErrors = false;
            var searchHighlighter = ServiceLocator.Instance.Get<ISearchHighlighter>();
            ServiceLocator.Instance.ReportErrors = oldState;

            if (searchHighlighter != null && searchHighlighter.Highlighter.Enabled)
            {
                var highlighter = searchHighlighter.Highlighter;

                var style = new Style(typeof(ListViewItem));
                var trigger = new DataTrigger
                                          {
                                              Binding = new Binding
                                                            {
                                                                ConverterParameter = highlighter,
                                                                Converter = new HighlighterConverter(highlighter),
                                                                Mode = BindingMode.OneWay
                                                            },
                                              Value = "Match"
                                          };

                if (highlighter.Style != null)
                {
                    if (highlighter.Style.Background != null)
                    {
                        trigger.Setters.Add(
                            new Setter(
                                Control.BackgroundProperty, new SolidColorBrush((Color)highlighter.Style.Background)));
                    }

                    if (highlighter.Style.Foreground != null)
                    {
                        trigger.Setters.Add(
                            new Setter(
                                Control.ForegroundProperty, new SolidColorBrush((Color)highlighter.Style.Foreground)));
                    }
                }

                style.Triggers.Add(trigger);
                SetStyleSpacing(style);
                styles[highlighter] = style;
            }

            var highlightingService = ServiceLocator.Instance.Get<IHighlightingService<IHighlighter>>();

            if (highlightingService != null)
            {
                foreach (var highlighter in highlightingService.Highlighters)
                {
                    if (highlighter != null)
                    {
                        // No need to create a style if not enabled, should the status of a highlighter
                        // change, then this collection will be rebuilt.
                        if (highlighter.Enabled)
                        {
                            var style = new Style(typeof(ListViewItem));

                            var trigger = new DataTrigger
                                {
                                    Binding =
                                        new Binding
                                            {
                                                ConverterParameter = highlighter,
                                                Converter = new HighlighterConverter(highlighter),
                                                Mode = BindingMode.OneWay
                                            },
                                    Value = "Match"
                                };

                            if (highlighter.Style != null)
                            {
                                if (highlighter.Style.Background != null)
                                {
                                    trigger.Setters.Add(
                                        new Setter(
                                            Control.BackgroundProperty,
                                            new SolidColorBrush((Color) highlighter.Style.Background)));
                                }

                                if (highlighter.Style.Foreground != null)
                                {
                                    trigger.Setters.Add(
                                        new Setter(
                                            Control.ForegroundProperty,
                                            new SolidColorBrush((Color) highlighter.Style.Foreground)));
                                }
                            }

                            // Top align values
                            style.Setters.Add(
                                new Setter(
                                    Control.VerticalContentAlignmentProperty,
                                    VerticalAlignment.Top));

                            style.Triggers.Add(trigger);
                            SetStyleSpacing(style);
                            styles[highlighter] = style;
                        }
                    }
                }
            }
        }
コード例 #22
0
        public override DependencyObject CreateTrigger(StyleSheet styleSheet, ITrigger trigger, Type targetType, DependencyObject styleResourceReferenceHolder)
        {
            if (trigger == null)
            {
                throw new ArgumentNullException(nameof(trigger));
            }

            if (trigger is Trigger)
            {
                var propertyTrigger = trigger as Trigger;
                var nativeTrigger   = new System.Windows.Trigger();

                var dependencyProperty = dependencyService.GetBindableProperty(targetType, propertyTrigger.Property);
                if (dependencyProperty == null)
                {
                    throw new NullReferenceException($"Property '{propertyTrigger.Property}' may not be null (targetType '{targetType.Name}')!");
                }

                nativeTrigger.Property = dependencyProperty;
                nativeTrigger.Value    = dependencyService.GetBindablePropertyValue(targetType, nativeTrigger.Property, propertyTrigger.Value);

                foreach (var styleDeclaration in propertyTrigger.StyleDeclarationBlock)
                {
                    var property = typeNameResolver.GetDependencyProperty(styleSheet.Namespaces, targetType, styleDeclaration.Property);
                    if (property == null)
                    {
                        continue;
                    }
                    try
                    {
                        var value = typeNameResolver.GetPropertyValue(targetType, styleResourceReferenceHolder, styleDeclaration.Value, property, styleSheet.Namespaces);

                        if (value is string valueString)
                        {
                            value = TypeDescriptor.GetConverter(property.PropertyType)?.ConvertFromInvariantString(valueString) ?? value;
                        }

                        nativeTrigger.Setters.Add(new Setter {
                            Property = property, Value = value
                        });
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in property trigger ""{propertyTrigger.Property} {propertyTrigger.Value} - {styleDeclaration.Property}: {styleDeclaration.Value}"": {e.Message}");
                    }
                }

                foreach (var action in propertyTrigger.EnterActions)
                {
                    try
                    {
                        var nativeTriggerAction = CreateTriggerAction(styleSheet, styleResourceReferenceHolder, action);

                        nativeTrigger.EnterActions.Add(nativeTriggerAction);
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in property trigger ""{propertyTrigger.Property} {propertyTrigger.Value}"" enter action: {e.Message}");
                    }
                }

                foreach (var action in propertyTrigger.ExitActions)
                {
                    try
                    {
                        var nativeTriggerAction = CreateTriggerAction(styleSheet, styleResourceReferenceHolder, action);

                        nativeTrigger.ExitActions.Add(nativeTriggerAction);
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in property trigger ""{propertyTrigger.Property} {propertyTrigger.Value}"" exit action: {e.Message}");
                    }
                }

                return(nativeTrigger);
            }
            else if (trigger is DataTrigger)
            {
                var dataTrigger   = trigger as DataTrigger;
                var nativeTrigger = new System.Windows.DataTrigger();

                var expression = "{Binding " + dataTrigger.Binding + "}";

                var binding = (System.Windows.Data.BindingBase)markupExtensionParser.ProvideValue(expression, null, styleSheet.Namespaces);
                nativeTrigger.Binding = binding;

                nativeTrigger.Value = GetBasicValue(dataTrigger);

                foreach (var styleDeclaration in dataTrigger.StyleDeclarationBlock)
                {
                    try
                    {
                        var property = typeNameResolver.GetDependencyProperty(styleSheet.Namespaces, targetType, styleDeclaration.Property);
                        if (property == null)
                        {
                            continue;
                        }

                        var value = typeNameResolver.GetPropertyValue(targetType, styleResourceReferenceHolder, styleDeclaration.Value, property, styleSheet.Namespaces);

                        if (value is string valueString)
                        {
                            value = TypeDescriptor.GetConverter(property.PropertyType)?.ConvertFromInvariantString(valueString) ?? value;
                        }

                        nativeTrigger.Setters.Add(new Setter {
                            Property = property, Value = value
                        });
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in data trigger ""{dataTrigger.Binding} {dataTrigger.Value} - {styleDeclaration.Property}: {styleDeclaration.Value}"": {e.Message}");
                    }
                }

                foreach (var action in dataTrigger.EnterActions)
                {
                    try
                    {
                        var nativeTriggerAction = CreateTriggerAction(styleSheet, styleResourceReferenceHolder, action);

                        nativeTrigger.EnterActions.Add(nativeTriggerAction);
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in data trigger ""{dataTrigger.Binding} {dataTrigger.Value} - {action}"" enter action: {e.Message}");
                    }
                }

                foreach (var action in dataTrigger.ExitActions)
                {
                    try
                    {
                        var nativeTriggerAction = CreateTriggerAction(styleSheet, styleResourceReferenceHolder, action);

                        nativeTrigger.ExitActions.Add(nativeTriggerAction);
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in data trigger ""{dataTrigger.Binding} {dataTrigger.Value} - {action}"" exit action: {e.Message}");
                    }
                }

                return(nativeTrigger);
            }
            else if (trigger is EventTrigger)
            {
                var eventTrigger  = trigger as EventTrigger;
                var nativeTrigger = new System.Windows.EventTrigger();

                var fieldInfo = targetType.GetField(eventTrigger.Event + "Event", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);

                nativeTrigger.RoutedEvent = (RoutedEvent)fieldInfo.GetValue(null);

                foreach (var action in eventTrigger.Actions)
                {
                    try
                    {
                        var nativeTriggerAction = CreateTriggerAction(styleSheet, styleResourceReferenceHolder, action);

                        nativeTrigger.Actions.Add(nativeTriggerAction);
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in event trigger ""{eventTrigger.Event} {action.Action}"": {e.Message}");
                    }
                }

                return(nativeTrigger);
            }

            throw new NotSupportedException($"Trigger '{trigger.GetType().FullName}' is not supported!");
        }
コード例 #23
0
ファイル: StyleService.cs プロジェクト: mingyaaaa/XamlCSS
        public override DependencyObject CreateTrigger(StyleSheet styleSheet, ITrigger trigger, Type targetType, DependencyObject styleResourceReferenceHolder)
        {
            if (trigger == null)
            {
                throw new ArgumentNullException(nameof(trigger));
            }

            if (trigger is Trigger)
            {
                var propertyTrigger = trigger as Trigger;
                var nativeTrigger   = new System.Windows.Trigger();

                var dependencyProperty = dependencyService.GetDependencyProperty(targetType, propertyTrigger.Property);
                if (dependencyProperty == null)
                {
                    throw new NullReferenceException($"Property '{propertyTrigger.Property}' may not be null (targetType '{targetType.Name}')!");
                }

                nativeTrigger.Property = dependencyProperty;
                nativeTrigger.Value    = dependencyService.GetDependencyPropertyValue(targetType, nativeTrigger.Property.Name, nativeTrigger.Property, propertyTrigger.Value);
                foreach (var styleDeclaration in propertyTrigger.StyleDeclarationBlock)
                {
                    var propertyInfo = typeNameResolver.GetDependencyPropertyInfo(styleSheet.Namespaces, targetType, styleDeclaration.Property);
                    if (propertyInfo == null)
                    {
                        continue;
                    }
                    try
                    {
                        var value = typeNameResolver.GetPropertyValue(propertyInfo.DeclaringType, styleResourceReferenceHolder, propertyInfo.Name, styleDeclaration.Value, propertyInfo.Property, styleSheet.Namespaces);
                        if (value == null)
                        {
                        }

                        nativeTrigger.Setters.Add(new Setter {
                            Property = propertyInfo.Property, Value = value
                        });
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in property trigger ""{propertyTrigger.Property} {propertyTrigger.Value} - {styleDeclaration.Property}: {styleDeclaration.Value}"": {e.Message}");
                    }
                }

                foreach (var action in propertyTrigger.EnterActions)
                {
                    try
                    {
                        var nativeTriggerAction = CreateTriggerAction(styleSheet, styleResourceReferenceHolder, action);

                        nativeTrigger.EnterActions.Add(nativeTriggerAction);
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in property trigger ""{propertyTrigger.Property} {propertyTrigger.Value}"" enter action: {e.Message}");
                    }
                }
                foreach (var action in propertyTrigger.ExitActions)
                {
                    try
                    {
                        var nativeTriggerAction = CreateTriggerAction(styleSheet, styleResourceReferenceHolder, action);

                        nativeTrigger.ExitActions.Add(nativeTriggerAction);
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in property trigger ""{propertyTrigger.Property} {propertyTrigger.Value}"" exit action: {e.Message}");
                    }
                }

                var serialized = SerializeObject(nativeTrigger);
                //serialized = $"pre XamlWriter.Save({nativeTrigger.GetType().Name})".Measure(() => XamlWriter.Save(nativeTrigger));

                Css.SetSerializedTrigger(nativeTrigger, serialized);

                return(nativeTrigger);
            }
            else if (trigger is DataTrigger)
            {
                var dataTrigger   = trigger as DataTrigger;
                var nativeTrigger = new System.Windows.DataTrigger();

                string expression = null;
                if (typeNameResolver.IsMarkupExtension(dataTrigger.Binding))
                {
                    expression = typeNameResolver.CreateMarkupExtensionExpression(dataTrigger.Binding);
                }
                else
                {
                    expression = "{Binding " + dataTrigger.Binding + "}";
                }

                var binding = (System.Windows.Data.BindingBase)markupExtensionParser.ProvideValue(expression, null, styleSheet.Namespaces);
                nativeTrigger.Binding = binding;

                nativeTrigger.Value = GetBasicValue(dataTrigger);

                foreach (var styleDeclaration in dataTrigger.StyleDeclarationBlock)
                {
                    try
                    {
                        var propertyInfo = typeNameResolver.GetDependencyPropertyInfo(styleSheet.Namespaces, targetType, styleDeclaration.Property);
                        if (propertyInfo == null)
                        {
                            continue;
                        }

                        var value = typeNameResolver.GetPropertyValue(propertyInfo.DeclaringType, styleResourceReferenceHolder, propertyInfo.Name, styleDeclaration.Value, propertyInfo.Property, styleSheet.Namespaces);
                        if (value == null)
                        {
                        }

                        nativeTrigger.Setters.Add(new Setter {
                            Property = propertyInfo.Property, Value = value
                        });
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in data trigger ""{dataTrigger.Binding} {dataTrigger.Value} - {styleDeclaration.Property}: {styleDeclaration.Value}"": {e.Message}");
                    }
                }

                foreach (var action in dataTrigger.EnterActions)
                {
                    try
                    {
                        System.Windows.TriggerAction nativeTriggerAction = null;

                        nativeTriggerAction = CreateTriggerAction(styleSheet, styleResourceReferenceHolder, action);

                        nativeTrigger.EnterActions.Add(nativeTriggerAction);
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in data trigger ""{dataTrigger.Binding} {dataTrigger.Value} - {action}"" enter action: {e.Message}");
                    }
                }

                foreach (var action in dataTrigger.ExitActions)
                {
                    try
                    {
                        var nativeTriggerAction = CreateTriggerAction(styleSheet, styleResourceReferenceHolder, action);

                        nativeTrigger.ExitActions.Add(nativeTriggerAction);
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in data trigger ""{dataTrigger.Binding} {dataTrigger.Value} - {action}"" exit action: {e.Message}");
                    }
                }

                var serialized = SerializeObject(nativeTrigger);
                //serialized = $"pre XamlWriter.Save({nativeTrigger.GetType().Name})".Measure(() => XamlWriter.Save(nativeTrigger));

                Css.SetSerializedTrigger(nativeTrigger, serialized);

                return(nativeTrigger);
            }
            else if (trigger is EventTrigger)
            {
                var eventTrigger  = trigger as EventTrigger;
                var nativeTrigger = new System.Windows.EventTrigger();

                nativeTrigger.RoutedEvent = (RoutedEvent)TypeHelpers.GetFieldValue(targetType, eventTrigger.Event + "Event");
                foreach (var action in eventTrigger.Actions)
                {
                    try
                    {
                        var nativeTriggerAction = CreateTriggerAction(styleSheet, styleResourceReferenceHolder, action);

                        nativeTrigger.Actions.Add(nativeTriggerAction);
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in event trigger ""{eventTrigger.Event} {action.Action}"": {e.Message}");
                    }
                }

                var serialized = SerializeObject(nativeTrigger);
                //serialized = $"pre XamlWriter.Save({nativeTrigger.GetType().Name})".Measure(() => XamlWriter.Save(nativeTrigger));

                Css.SetSerializedTrigger(nativeTrigger, serialized);

                return(nativeTrigger);
            }

            throw new NotSupportedException($"Trigger '{trigger.GetType().FullName}' is not supported!");
        }
コード例 #24
0
        // Given a single data trigger and associated context information,
        //  evaluate the old and new states of the trigger.
        private static void EvaluateOldNewStates( DataTrigger dataTrigger,
            DependencyObject triggerContainer,
            BindingBase binding, BindingValueChangedEventArgs bindingChangedArgs, UncommonField<HybridDictionary[]> dataField,
            Style style, FrameworkTemplate frameworkTemplate,
            out bool oldState, out bool newState )
        {
            TriggerCondition[] conditions = dataTrigger.TriggerConditions;
            Debug.Assert( conditions != null && conditions.Length == 1,
                "This method assumes there is exactly one TriggerCondition." );

            oldState = conditions[0].ConvertAndMatch(bindingChangedArgs.OldValue);
            newState = conditions[0].ConvertAndMatch(bindingChangedArgs.NewValue);
        }