/// <summary>
        /// Update the selected value of the of the TreeView based on the value
        /// of the currently selected TreeViewItem and the SelectedValuePath.
        /// </summary>
        /// <param name="item">
        /// Value of the currently selected TreeViewItem.
        /// </param>
        private void UpdateSelectedValue(object item)
        {
            if (item != null)
            {
                string path = SelectedValuePath;
                if (string.IsNullOrEmpty(path))
                {
                    SelectedValue = item;
                }
                else
                {
                    // Since we don't have the ability to evaluate a
                    // BindingExpression, we'll just create a new temporary
                    // control to bind the value to which we can then copy out
                    Binding binding = new Binding(path)
                    {
                        Source = item
                    };
                    ContentControl temp = new ContentControl();
                    temp.SetBinding(ContentControl.ContentProperty, binding);
                    SelectedValue = temp.Content;

                    // Remove the Binding once we have the value (this is
                    // especially important if the value is a UIElement because
                    // it should not exist in the visual tree once we've
                    // finished)
                    temp.ClearValue(ContentControl.ContentProperty);
                }
            }
            else
            {
                ClearValue(SelectedValueProperty);
            }
        }
示例#2
0
        // Be sure to call the base class constructor.
        public ContentAdorner(UIElement adornedElement)
            : base(adornedElement)
        {
            this.children = new VisualCollection(this);

            //
            // Create the content control
            //
            var contentControl = new ContentControl();

            //
            // Bind the content control to the Adorner's ContentTemplate property, so we know what to display
            //
            var contentTemplateBinding = new Binding();
            contentTemplateBinding.Path = new PropertyPath(AdornerContentTemplateProperty);
            contentTemplateBinding.Source = adornedElement;
            contentControl.SetBinding(ContentControl.ContentTemplateProperty, contentTemplateBinding);

            //
            // Add the ContentControl as a child
            //
            this.child = contentControl;
            this.children.Add(this.child);
            this.AddLogicalChild(this.child);
        }
示例#3
0
 protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
 { 
   var binding = new Binding(((Binding)Binding).Path.Path); 
   binding.Source = dataItem; 
  var content = new ContentControl(); 
  content.ContentTemplate = (DataTemplate)cell.FindResource(TemplateName); 
  content.SetBinding(ContentControl.ContentProperty, binding); return content; 
 } 
        /// <summary>
        /// Updates the specified binding.
        /// </summary>
        /// <param name="binding">The binding.</param>
        /// <param name="dataContext">The data context.</param>
        /// <param name="value">The value.</param>
        public static void Update(this BindingBase binding, object dataContext, object value)
        {
            Binding b = binding as Binding;
            if (b != null && b.Mode != BindingMode.TwoWay)
            {
                b.Mode = BindingMode.TwoWay;
            }

            ContentControl contentControl = new ContentControl();
            contentControl.DataContext = dataContext;
            contentControl.SetBinding(ContentControl.ContentProperty, b);
            contentControl.Content = value;
        }
        /// <summary>
        /// Resolves the specified binding.
        /// </summary>
        /// <param name="binding">The binding.</param>
        /// <param name="dataContext">The data context.</param>
        /// <returns>The result of the resolved binding.</returns>
        public static object Resolve(this BindingBase binding, object dataContext)
        {
            ContentControl contentControl = new ContentControl();
            contentControl.DataContext = dataContext;
            contentControl.SetBinding(ContentControl.ContentProperty, binding);

            if (!string.IsNullOrEmpty(binding.StringFormat))
            {
                contentControl.Content = string.Format(binding.StringFormat, contentControl.Content);
            }

            return contentControl.Content;
        }
示例#6
0
文件: Test.cs 项目: dfr0/moon
		void RunTest ()
		{
			var c = new ObservableCollection<int> { 1, 2, 3, 4, 5 };
			WeakControl = new ContentControl ();
			WeakControl.SetBinding (ContentControl.ContentProperty, new Binding ("[0]") { Source = c });
			Holder = c;

			GCAndInvoke (() => {
				if (WeakControl != null)
					Fail ("The control should be collected");
				else
					Succeed ();
			});
		}
示例#7
0
文件: Test.cs 项目: dfr0/moon
		void RunTest ()
		{
			var c = new CollectionViewSource {
				Source = new[] { 1, 2, 3, 4, 5 }
			};
			WeakControl = new ContentControl ();
			WeakControl.SetBinding (ContentControl.ContentProperty, new Binding ("") { Source = c.View });
			Holder = c;

			GCAndInvoke (() => {
				if (WeakControl != null)
					Fail ("The control should be collected");
				else
					Succeed ();
			});
		}
        public UIBoundToCustomerIndexer()
        {
            var stack = new StackPanel();
            Content = stack;

            var textBlock = new TextBlock();
            textBlock.SetBinding(TextBlock.TextProperty, new Binding("FirstName"));
            stack.Children.Add(textBlock);

            var contentControl = new ContentControl();
            contentControl.SetBinding(ContentControl.ContentProperty, new Binding("[0].Quantity"));
            stack.Children.Add(contentControl);

            contentControl = new ContentControl();
            contentControl.SetBinding(ContentControl.ContentProperty, new Binding("[text].Quaity")); //purposefully misspelled
            stack.Children.Add(contentControl);
        }
        public UIBoundToCustomerWithContentControlAndTriggers()
        {
            var stack = new StackPanel();
            Content = stack;

            var textBlock = new TextBlock();
            textBlock.SetBinding(TextBlock.TextProperty, new Binding("FirstName"));
            stack.Children.Add(textBlock);

            textBlock = new TextBlock();
            textBlock.SetBinding(TextBlock.TextProperty, new Binding("LastName"));
            stack.Children.Add(textBlock);

            var contentControl = new ContentControl {ContentTemplate = CreateItemTemplate()};
            contentControl.SetBinding(ContentControl.ContentProperty, new Binding("MailingAddress"));
            stack.Children.Add(contentControl);
        }
        public void ControlWithExistingBindingOnContentWithNullValueThrows()
        {
            var control = new ContentControl();
            Binding binding = new Binding("ObjectContents");
            binding.Source = new SimpleModel() { ObjectContents = null };
            control.SetBinding(ContentControl.ContentProperty, binding);

            IRegionAdapter adapter = new TestableContentControlRegionAdapter();

            try
            {
                var region = (MockPresentationRegion)adapter.Initialize(control, "Region1");
                Assert.Fail();
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(ex, typeof(InvalidOperationException));
                StringAssert.Contains(ex.Message, "ContentControl's Content property is not empty.");
            }
        }
        private void CreateOrUnhideDockableContent(ContentTypes contentType, string title, string viewPropertyName, object parent)
        {
            if (!this.dockableContents.Keys.Contains(contentType))
            {
                DockableContent dockableContent = new DockableContent();

                ContentControl contentControl = new ContentControl();

                dockableContent.IsCloseable = true;
                dockableContent.HideOnClose = false;

                dockableContent.Title = title;

                dockableContent.Content = contentControl;

                if (parent is ResizingPanel)
                {
                    DockablePane dockablePane = new DockablePane();
                    dockablePane.Items.Add(dockableContent);
                    ResizingPanel resizingPanel = parent as ResizingPanel;

                    switch (contentType)
                    {
                        case ContentTypes.PropertyInspector:
                            resizingPanel.Children.Add(dockablePane);
                            ResizingPanel.SetResizeWidth(dockablePane, new GridLength(300));
                            break;
                        case ContentTypes.Outline:
                            resizingPanel.Children.Insert(1, dockablePane);
                            ResizingPanel.SetResizeWidth(dockablePane, new GridLength(250));
                            break;
                        case ContentTypes.Toolbox:
                            resizingPanel.Children.Insert(0, dockablePane);
                            ResizingPanel.SetResizeWidth(dockablePane, new GridLength(250));
                            break;
                    }
                }
                else if (parent is DockablePane)
                {
                    DockablePane dockablePane = parent as DockablePane;
                    dockablePane.Items.Add(dockableContent);
                    if (dockablePane.Parent == null)
                    {
                        this.verticalResizingPanel.Children.Add(dockablePane);
                    }
                }

                Binding dataContextBinding = new Binding(viewPropertyName);
                dockableContent.SetBinding(DockableContent.DataContextProperty, dataContextBinding);

                Binding contentBinding = new Binding(".");
                contentControl.SetBinding(ContentControl.ContentProperty, contentBinding);

                this.dockableContents[contentType] = dockableContent;

                dockableContent.Closed += delegate(object sender, EventArgs args)
                {
                    contentControl.Content = null;
                    this.dockableContents[contentType].DataContext = null;
                    this.dockableContents.Remove(contentType);
                };
            }
            else
            {
                if (this.dockableContents[contentType].State == DockableContentState.Hidden)
                {
                    this.dockableContents[contentType].Show();
                }
            }
        }
        /// <summary>
        /// Adds <see cref="TabItem"/> for the content object
        /// </summary>
        /// <param name="item">Content of the <see cref="TabItems"/></param>
        private void AddTabItem(object item)
        {
            ContentControl contentControl = new ContentControl();
            TabItem tab = new TabItem
            {
                DataContext = item,
                Content = contentControl,
                HeaderTemplate = _tabControl.ItemTemplate
            };

            contentControl.SetBinding(ContentControl.ContentProperty, new Binding());
            tab.SetBinding(TabItem.HeaderProperty, new Binding());

            _tabControl.Items.Add(tab);
        }
示例#13
0
文件: BindingTest.cs 项目: dfr0/moon
		public void DataContext_PreferFrameworkElementParentOverMentor ()
		{
			var root1 = new Canvas { DataContext = 1 };
			var root2 = new Canvas { DataContext = 2 };

			var target = new ContentControl ();
			target.SetBinding (FrameworkElement.DataContextProperty, new Binding ());

			// This sets FrameworkElement.Parent
			root1.Children.Add (target);

			// This sets a new Mentor
			ToolTipService.SetPlacementTarget (root2, target);
			CreateAsyncTest (root1,
				() => {
					// We should be using the DataContext from FrameworkElement.Parent, not the mentor
					Assert.AreEqual (1, target.DataContext, "#1");
					// We pick up changes on the datacontext
					root1.DataContext = 2;
				}, () => {
					Assert.AreEqual (2, target.DataContext, "#2");

					// We ignore changes on the mentors datacontext
					root2.DataContext = 4;
				}, () => {
					Assert.AreEqual (2, target.DataContext, "#3");
				}
			);
		}
示例#14
0
        public void InDesignModeSettingViewModelWithGoodBindingGivesAppropriateMessage()
        {
            Execute.InDesignMode = true;

            var element = new ContentControl();
            var vm = new TestViewModel();

            var binding = new Binding("SubViewModel");
            binding.Source = vm;
            element.SetBinding(View.ModelProperty, binding);

            Assert.IsInstanceOf<TextBlock>(element.Content);

            var content = (TextBlock)element.Content;
            Assert.AreEqual("View for TestViewModel.SubViewModel", content.Text);
        }
示例#15
0
        // Find out the value of the item using SelectedValuePath.
        // If there is no SelectedValuePath then item itself is
        // it's value or the innerText in case of XML node.
        private object GetSelectableValueFromItem(object item, ContentControl dummyElement)
        {
            bool useXml = item is XmlNode;
            Binding itemBinding = new Binding();
            itemBinding.Source = item;
            if (useXml)
            {
                itemBinding.XPath = SelectedValuePath;
                itemBinding.Path = new PropertyPath("/InnerText");
            }
            else
            {
                itemBinding.Path = new PropertyPath(SelectedValuePath);
            }

            // optimize for case where there is no SelectedValuePath (meaning
            // that the value of the item is the item itself, or the InnerText
            // of the item)
            if (string.IsNullOrEmpty(SelectedValuePath))
            {
                // when there's no SelectedValuePath, the binding's Path
                // is either empty (CLR) or "/InnerText" (XML)
                string path = itemBinding.Path.Path;
                Debug.Assert(String.IsNullOrEmpty(path) || path == "/InnerText");
                if (string.IsNullOrEmpty(path))
                {
                    // CLR - item is its own selected value
                    return item;
                }
                else
                {
                    return GetInnerText(item);
                }
            }

            dummyElement.SetBinding(ContentControl.ContentProperty, itemBinding);
            return dummyElement.Content;
        }
		public GlyphIconButton_WithPopup()
		{
			Popup = new Popup()
			{
				AllowsTransparency = true,
			};
			var contentControl = new ContentControl()
			{
				Focusable = false,
				IsTabStop = false,

			};
			contentControl.SetBinding(ContentProperty, new Binding() {Source = this, Path = new PropertyPath($"{nameof(PopupContent)}")});
			contentControl.SetBinding(ContentTemplateProperty, new Binding() {Source = this, Path = new PropertyPath($"{nameof(PopupContentTemplate)}")});
			Popup.Child = new Border
			{
				Child = contentControl,
				Effect = new DropShadowEffect() {BlurRadius = 10, Color = Colors.Black, Opacity = 1, ShadowDepth = 0},
				Margin = new Thickness(10),
			};
			Popup.SetBinding(Popup.IsOpenProperty, new Binding() {Source = this, Path = new PropertyPath($"{nameof(IsOpened)}")});
			Popup.SetBinding(Popup.PlacementTargetProperty, new Binding() {Source = this, Path = new PropertyPath($"{nameof(PopupPlacementTarget)}")});
			Popup.SetBinding(Popup.StaysOpenProperty, new Binding() {Source = this, Path = new PropertyPath($"{nameof(StaysOpen)}")});
			Popup.Placement = PlacementMode.Bottom;
			AddLogicalChild(Popup);
			Click += GlyphIconButton_WithPopup_Click;
		}
        /// <summary>
        /// Initializes a new instance of the <see cref="CalendarMonthView"/> class.
        /// </summary>
        public CalendarMonthView()
        {
            InitializeComponent();

            DayItemTemplate = (ControlTemplate)Resources["DayItemTemplate"];

            for (int row = 0; row < 6; row++)
            {
                for (int column = 0; column < 7; column++)
                {
                    CalendarMonthViewDayModel model = new CalendarMonthViewDayModel { MonthPosition = new DayInMonthViewPosition(row, column, IsInPortrait) };
                    ContentControl dayControl = new ContentControl { DataContext = model };

                    dayControl.SetBinding(ContentControl.TemplateProperty, new Binding("DayItemTemplate") { Source = this });
                    dayControl.Tap += new EventHandler<GestureEventArgs>(DayControl_Tap);

                    Grid.SetRow(dayControl, row);
                    Grid.SetColumn(dayControl, column);
                    CalendarGrid.Children.Add(dayControl);
                }
            }

            SetValue(DateProperty, new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1));
            UpdateDayNames();
            CalendarMonthViewDayModel todayModel = GetTodayModel();
            if (todayModel != null)
            {
                CurrentDay = todayModel.DateTime;
            }
        }
示例#18
0
 FrameworkElement AddChild(UIElement elm, int i)
 {
     var proxy = new LayoutProxy(elm);
     Grid.SetColumnSpan(proxy, Grid.GetColumnSpan(elm));
     Grid.SetRow(proxy, i);
     Grid.SetColumn(proxy, 0);
     var sideContentPresenter = new ContentControl { ContentTemplate = SideContentTemplate };
     var binding = new Binding("DataContext") { Source = elm };
     sideContentPresenter.SetBinding(ContentControl.ContentProperty, binding);
     var sideContentWrapper = new LayoutProxy(sideContentPresenter);
     Grid.SetRow(sideContentWrapper, i);
     Grid.SetColumn(sideContentWrapper, 1);
     this.AddVisualChild(sideContentPresenter);
     innerGrid.Children.Add(proxy);
     innerGrid.Children.Add(sideContentWrapper);
     return sideContentPresenter;
 }
示例#19
0
        /// <summary>
        /// Creates the property panel.
        /// </summary>
        /// <param name="pi">
        /// The pi.
        /// </param>
        /// <param name="instance">
        /// The instance.
        /// </param>
        /// <param name="maxLabelWidth">
        /// Width of the max label.
        /// </param>
        /// <returns>
        /// The property panel.
        /// </returns>
        private UIElement CreatePropertyPanel(PropertyItem pi, object instance, ref double maxLabelWidth)
        {
            var propertyPanel = new DockPanel { Margin = new Thickness(2) };
            var propertyLabel = this.CreateLabel(pi);
            var propertyControl = this.CreatePropertyControl(pi);
            if (propertyControl != null)
            {
                if (!double.IsNaN(pi.Width))
                {
                    propertyControl.Width = pi.Width;
                    propertyControl.HorizontalAlignment = HorizontalAlignment.Left;
                }

                if (!double.IsNaN(pi.Height))
                {
                    propertyControl.Height = pi.Height;
                }

                if (!double.IsNaN(pi.MinimumHeight))
                {
                    propertyControl.MinHeight = pi.MinimumHeight;
                }

                if (!double.IsNaN(pi.MaximumHeight))
                {
                    propertyControl.MaxHeight = pi.MaximumHeight;
                }

                if (pi.IsOptional)
                {
                    if (pi.OptionalDescriptor != null)
                    {
                        propertyControl.SetBinding(IsEnabledProperty, new Binding(pi.OptionalDescriptor.Name));
                    }
                    else
                    {
                        propertyControl.SetBinding(
                            IsEnabledProperty, new Binding(pi.Descriptor.Name) { Converter = NullToBoolConverter });
                    }
                }

                if (instance is IDataErrorInfo)
                {
                    if (this.ValidationTemplate != null)
                    {
                        Validation.SetErrorTemplate(propertyControl, this.ValidationTemplate);
                    }

                    if (this.ValidationErrorStyle != null)
                    {
                        propertyControl.Style = this.ValidationErrorStyle;
                    }

                    var errorControl = new ContentControl { ContentTemplate = this.ValidationErrorTemplate };
                    errorControl.SetBinding(
                        VisibilityProperty,
                        new Binding("(Validation.HasError)")
                            {
                                Source = propertyControl,
                                Converter = BoolToVisibilityConverter
                            });
                    errorControl.SetBinding(
                        ContentControl.ContentProperty, new Binding("(Validation.Errors)") { Source = propertyControl });

                    // replace the property control by a stack panel containig the property control and the error control.
                    var sp = new StackPanel();
                    sp.VerticalAlignment = VerticalAlignment.Center;
                    sp.Children.Add(propertyControl);
                    sp.Children.Add(errorControl);
                    propertyControl = sp;
                }
            }

            var actualHeaderPlacement = pi.HeaderPlacement;

            if (!this.ShowCheckBoxHeaders && propertyControl is CheckBox)
            {
                actualHeaderPlacement = HeaderPlacement.Collapsed;
                var cb = propertyControl as CheckBox;
                cb.Content = propertyLabel;

                propertyLabel = null;
            }

            switch (actualHeaderPlacement)
            {
                case HeaderPlacement.Hidden:
                    {
                        var labelPanel = new DockPanel();
                        labelPanel.SetBinding(MinWidthProperty, new Binding("ActualLabelWidth") { Source = this });
                        propertyPanel.Children.Add(labelPanel);
                        break;
                    }

                case HeaderPlacement.Collapsed:
                    break;
                default:
                    {
                        // create the label panel
                        var labelPanel = new DockPanel();
                        if (pi.HeaderPlacement == HeaderPlacement.Left)
                        {
                            DockPanel.SetDock(labelPanel, Dock.Left);
                            labelPanel.SetBinding(MinWidthProperty, new Binding("ActualLabelWidth") { Source = this });
                        }
                        else
                        {
                            DockPanel.SetDock(labelPanel, Dock.Top);
                        }

                        propertyPanel.Children.Add(labelPanel);

                        if (propertyLabel != null)
                        {
                            DockPanel.SetDock(propertyLabel, Dock.Left);
                            labelPanel.Children.Add(propertyLabel);
                        }

                        if (this.ShowDescriptionIcons && this.DescriptionIcon != null)
                        {
                            if (!string.IsNullOrWhiteSpace(pi.Description))
                            {
                                var descriptionIconImage = new Image
                                    {
                                        Source = this.DescriptionIcon,
                                        Stretch = Stretch.None,
                                        Margin = new Thickness(0, 4, 4, 4),
                                        VerticalAlignment = VerticalAlignment.Top
                                    };

                                // RenderOptions.SetBitmapScalingMode(descriptionIconImage, BitmapScalingMode.NearestNeighbor);
                                descriptionIconImage.HorizontalAlignment = this.DescriptionIconAlignment;
                                labelPanel.Children.Add(descriptionIconImage);
                                if (!string.IsNullOrWhiteSpace(pi.Description))
                                {
                                    descriptionIconImage.ToolTip = this.CreateToolTip(pi.Description);
                                }
                            }
                        }
                        else
                        {
                            labelPanel.ToolTip = this.CreateToolTip(pi.Description);
                        }

                        // measure the size of the label and tooltip icon
                        labelPanel.Measure(new Size(this.ActualWidth, this.ActualHeight));
                        maxLabelWidth = Math.Max(maxLabelWidth, labelPanel.DesiredSize.Width);
                    }

                    break;
            }

            // add the property control
            if (propertyControl != null)
            {
                propertyPanel.Children.Add(propertyControl);
            }

            if (pi.IsEnabledDescriptor != null)
            {
                propertyPanel.SetBinding(IsEnabledProperty, new Binding(pi.IsEnabledDescriptor.Name));
            }

            if (pi.IsVisibleDescriptor != null)
            {
                propertyPanel.SetBinding(
                    VisibilityProperty,
                    new Binding(pi.IsVisibleDescriptor.Name) { Converter = BoolToVisibilityConverter });
            }

            return propertyPanel;
        }
示例#20
0
        public FrameworkElement BuildGUIConfiguration()
        {
            Grid grid = new Grid();
            grid.RowDefinitions.Add(new RowDefinition());
            grid.RowDefinitions.Add(new RowDefinition());
            grid.ColumnDefinitions.Add(new ColumnDefinition());
            grid.ColumnDefinitions.Add(new ColumnDefinition());

            Label l = new Label() { Content = "Mode: " };
            grid.Children.Add(l);
            Grid.SetRow(l, 0);
            Grid.SetColumn(l, 0);

            // Combobox
            ComboBox combo = new ComboBox() { VerticalAlignment = VerticalAlignment.Center };
            combo.SetBinding(ComboBox.SelectedItemProperty, new Binding("SelectedMode"));

            // Combo percentage mode
            Grid modeGrid = new Grid();
            modeGrid.ColumnDefinitions.Add(new ColumnDefinition());
            modeGrid.ColumnDefinitions.Add(new ColumnDefinition());

            Mode percentageMode = new Mode() { Name = "Percentage", RankMode = RankSelector.SelectionMode.Percentage };

            l = new Label() { Content = "Percentage:" };
            modeGrid.Children.Add(l);
            Grid.SetColumn(l, 0);

            TextBox tb = new TextBox() { VerticalAlignment = VerticalAlignment.Center };
            tb.SetBinding(TextBox.TextProperty, new Binding("Percentage"));
            modeGrid.Children.Add(tb);
            Grid.SetColumn(tb, 1);

            percentageMode.ModeGUI = modeGrid;

            // Number mode
            modeGrid = new Grid();
            modeGrid.ColumnDefinitions.Add(new ColumnDefinition());
            modeGrid.ColumnDefinitions.Add(new ColumnDefinition());

            Mode numberMode = new Mode() { Name = "Best N", RankMode = RankSelector.SelectionMode.Number };

            l = new Label() { Content = "N:" };
            modeGrid.Children.Add(l);
            Grid.SetColumn(l, 0);

            tb = new TextBox() { VerticalAlignment = VerticalAlignment.Center };
            tb.SetBinding(TextBox.TextProperty, new Binding("Number"));
            modeGrid.Children.Add(tb);
            Grid.SetColumn(tb, 1);

            numberMode.ModeGUI = modeGrid;

            combo.ItemsSource = new ObservableCollection<Mode>() { percentageMode, numberMode };

            grid.Children.Add(combo);
            Grid.SetRow(combo, 0);
            Grid.SetColumn(combo, 1);

            ContentControl c = new ContentControl();
            c.SetBinding(ContentControl.ContentProperty, new Binding("SelectedMode.ModeGUI"));

            grid.Children.Add(c);
            Grid.SetRow(c, 1);
            Grid.SetColumn(c, 0);
            Grid.SetColumnSpan(c, 2);

            return grid;
        }
示例#21
0
文件: BindingTest.cs 项目: dfr0/moon
		public void DataContext_PreferFrameworkElementParentOverMentor_ParentAlwaysNull ()
		{
			var root1 = new Canvas { DataContext = 1 };
			var root2 = new Canvas { DataContext = 2 };

			var target = new ContentControl ();
			target.SetBinding (FrameworkElement.DataContextProperty, new Binding ());

			// This sets a new Mentor
			ToolTipService.SetPlacementTarget (root2, target);

			CreateAsyncTest (root1,
				() => {
					// We don't use the Mentors DataContext even though it's the only one
					Assert.IsNull (target.DataContext, "#1");
					root2.DataContext = 3;
				}, () => {
					Assert.IsNull (target.DataContext, "#2");
				}
			);
		}
示例#22
0
        /// <summary>
        /// Update the selected value of the of the TreeView based on the value
        /// of the currently selected TreeViewItem and the SelectedValuePath.
        /// </summary>
        /// <param name="item">
        /// Value of the currently selected TreeViewItem.
        /// </param>
        private void UpdateSelectedValue(object item)
        {
            if (item != null)
            {
                string path = SelectedValuePath;
                if (string.IsNullOrEmpty(path))
                {
                    SelectedValue = item;
                }
                else
                {
                    // Since we don't have the ability to evaluate a
                    // BindingExpression, we'll just create a new temporary
                    // control to bind the value to which we can then copy out
                    Binding binding = new Binding(path) { Source = item };
                    ContentControl temp = new ContentControl();
                    temp.SetBinding(ContentControl.ContentProperty, binding);
                    SelectedValue = temp.Content;

                    // Remove the Binding once we have the value (this is
                    // especially important if the value is a UIElement because
                    // it should not exist in the visual tree once we've
                    // finished)
                    temp.ClearValue(ContentControl.ContentProperty);
                }
            }
            else
            {
                ClearValue(SelectedValueProperty);
            }
        }
 /// <summary>
 /// Creates a control based on a template from a a <see cref="TypeEditor" />.
 /// </summary>
 /// <param name="property">The property.</param>
 /// <param name="editor">The editor.</param>
 /// <returns>
 /// A <see cref="ContentControl" />.
 /// </returns>
 protected virtual ContentControl CreateEditorControl(PropertyItem property, TypeEditor editor)
 {
     var c = new ContentControl
     {
         ContentTemplate = editor.EditorTemplate,
         VerticalAlignment = VerticalAlignment.Center,
         HorizontalAlignment = HorizontalAlignment.Left
     };
     c.SetBinding(FrameworkElement.DataContextProperty, property.CreateOneWayBinding());
     return c;
 }
示例#24
0
        private void AddPropertyPanel(Panel panel, PropertyItem pi, object instance, Tab tab)
        {
            // TODO: refactor this method - too long and complex...
            var propertyPanel = new Grid();
            if (!pi.FillTab)
            {
                propertyPanel.Margin = new Thickness(2);
            }

            var labelColumn = new System.Windows.Controls.ColumnDefinition
                                  {
                                      Width = GridLength.Auto,
                                      MinWidth = this.MinimumLabelWidth,
                                      MaxWidth = this.MaximumLabelWidth,
                                      SharedSizeGroup =
                                          this.LabelWidthSharing
                                          != LabelWidthSharing.NotShared
                                              ? "labelColumn"
                                              : null
                                  };

            propertyPanel.ColumnDefinitions.Add(labelColumn);
            propertyPanel.ColumnDefinitions.Add(new System.Windows.Controls.ColumnDefinition());
            var rd = new System.Windows.Controls.RowDefinition
                         {
                             Height =
                                 pi.FillTab
                                     ? new GridLength(1, GridUnitType.Star)
                                     : GridLength.Auto
                         };
            propertyPanel.RowDefinitions.Add(rd);

            var propertyLabel = this.CreateLabel(pi);
            var propertyControl = this.CreatePropertyControl(pi);
            if (propertyControl != null)
            {
                if (!double.IsNaN(pi.Width))
                {
                    propertyControl.Width = pi.Width;
                    propertyControl.HorizontalAlignment = HorizontalAlignment.Left;
                }

                if (!double.IsNaN(pi.Height))
                {
                    propertyControl.Height = pi.Height;
                }

                if (!double.IsNaN(pi.MinimumHeight))
                {
                    propertyControl.MinHeight = pi.MinimumHeight;
                }

                if (!double.IsNaN(pi.MaximumHeight))
                {
                    propertyControl.MaxHeight = pi.MaximumHeight;
                }

                if (pi.IsOptional)
                {
                    propertyControl.SetBinding(
                        IsEnabledProperty,
                        pi.OptionalDescriptor != null ? new Binding(pi.OptionalDescriptor.Name) : new Binding(pi.Descriptor.Name) { Converter = NullToBoolConverter });
                }

                if (pi.IsEnabledByRadioButton)
                {
                    propertyControl.SetBinding(
                        IsEnabledProperty,
                        new Binding(pi.RadioDescriptor.Name) { Converter = new EnumToBooleanConverter() { EnumType = pi.RadioDescriptor.PropertyType }, ConverterParameter = pi.RadioValue });
                }

                var dataErrorInfoInstance = instance as IDataErrorInfo;
                if (dataErrorInfoInstance != null)
                {
                    if (this.ValidationTemplate != null)
                    {
                        Validation.SetErrorTemplate(propertyControl, this.ValidationTemplate);
                    }

                    if (this.ValidationErrorStyle != null)
                    {
                        propertyControl.Style = this.ValidationErrorStyle;
                    }

                    var errorControl = new ContentControl
                                           {
                                               ContentTemplate = this.ValidationErrorTemplate,
                                               Focusable = false
                                           };
                    var errorConverter = new DataErrorInfoConverter(dataErrorInfoInstance, pi.PropertyName);
                    var visibilityBinding = new Binding(pi.PropertyName)
                                      {
                                          Converter = errorConverter,
                                          NotifyOnTargetUpdated = true,
                                          //                                          ValidatesOnDataErrors = false,
#if !NET40
                                          ValidatesOnNotifyDataErrors = false,
#endif
                                          //                                          ValidatesOnExceptions = false
                                      };
                    errorControl.SetBinding(VisibilityProperty, visibilityBinding);

                    // When the visibility of the error control is changed, updated the HasErrors of the tab
                    errorControl.TargetUpdated += (s, e) => tab.UpdateHasErrors(dataErrorInfoInstance);

                    var contentBinding = new Binding(pi.PropertyName)
                                             {
                                                 Converter = errorConverter,
                                                 //                                                 ValidatesOnDataErrors = false,
#if !NET40
                                                 ValidatesOnNotifyDataErrors = false,
#endif
                                                 //                                                 ValidatesOnExceptions = false
                                             };
                    errorControl.SetBinding(ContentControl.ContentProperty, contentBinding);

                    // Add a row to the panel
                    propertyPanel.RowDefinitions.Add(new System.Windows.Controls.RowDefinition { Height = GridLength.Auto });
                    propertyPanel.Children.Add(errorControl);
                    Grid.SetRow(errorControl, 1);
                    Grid.SetColumn(errorControl, 1);
                }

                Grid.SetColumn(propertyControl, 1);
            }

            var actualHeaderPlacement = pi.HeaderPlacement;

            var checkBoxPropertyControl = propertyControl as CheckBox;

            if (checkBoxPropertyControl != null)
            {
                if (this.CheckBoxLayout != CheckBoxLayout.Header)
                {
                    checkBoxPropertyControl.Content = propertyLabel;
                    propertyLabel = null;
                }

                if (this.CheckBoxLayout == CheckBoxLayout.CollapseHeader)
                {
                    actualHeaderPlacement = HeaderPlacement.Collapsed;
                }
            }

            switch (actualHeaderPlacement)
            {
                case HeaderPlacement.Hidden:
                    break;

                case HeaderPlacement.Collapsed:
                    {
                        if (propertyControl != null)
                        {
                            Grid.SetColumn(propertyControl, 0);
                            Grid.SetColumnSpan(propertyControl, 2);
                        }

                        break;
                    }

                default:
                    {
                        // create the label panel
                        var labelPanel = new DockPanel();
                        if (pi.HeaderPlacement == HeaderPlacement.Left)
                        {
                            DockPanel.SetDock(labelPanel, Dock.Left);
                        }
                        else
                        {
                            // Above
                            if (propertyControl != null)
                            {
                                propertyPanel.RowDefinitions.Add(new System.Windows.Controls.RowDefinition());
                                Grid.SetColumnSpan(labelPanel, 2);
                                Grid.SetRow(propertyControl, 1);
                                Grid.SetColumn(propertyControl, 0);
                                Grid.SetColumnSpan(propertyControl, 2);
                            }
                        }

                        propertyPanel.Children.Add(labelPanel);

                        if (propertyLabel != null)
                        {
                            DockPanel.SetDock(propertyLabel, Dock.Left);
                            labelPanel.Children.Add(propertyLabel);
                        }

                        if (this.ShowDescriptionIcons && this.DescriptionIcon != null)
                        {
                            if (!string.IsNullOrWhiteSpace(pi.Description))
                            {
                                var descriptionIconImage = new Image
                                                               {
                                                                   Source = this.DescriptionIcon,
                                                                   Stretch = Stretch.None,
                                                                   Margin = new Thickness(0, 4, 4, 4),
                                                                   VerticalAlignment = VerticalAlignment.Top,
                                                                   HorizontalAlignment =
                                                                       this.DescriptionIconAlignment
                                                               };

                                // RenderOptions.SetBitmapScalingMode(descriptionIconImage, BitmapScalingMode.NearestNeighbor);
                                labelPanel.Children.Add(descriptionIconImage);
                                if (!string.IsNullOrWhiteSpace(pi.Description))
                                {
                                    descriptionIconImage.ToolTip = this.CreateToolTip(pi.Description);
                                }
                            }
                        }
                        else
                        {
                            labelPanel.ToolTip = this.CreateToolTip(pi.Description);
                        }
                    }

                    break;
            }

            // add the property control
            if (propertyControl != null)
            {
                propertyPanel.Children.Add(propertyControl);
            }

            // Set the IsEnabled binding of the label
            if (pi.IsEnabledDescriptor != null && propertyLabel != null)
            {
                var isEnabledBinding = new Binding(pi.IsEnabledDescriptor.Name);
                if (pi.IsEnabledValue != null)
                {
                    isEnabledBinding.ConverterParameter = pi.IsEnabledValue;
                    isEnabledBinding.Converter = ValueToBooleanConverter;
                }

                propertyLabel.SetBinding(IsEnabledProperty, isEnabledBinding);
            }

            // Set the IsEnabled binding of the property control
            if (pi.IsEnabledDescriptor != null && propertyControl != null)
            {
                var isEnabledBinding = new Binding(pi.IsEnabledDescriptor.Name);
                if (pi.IsEnabledValue != null)
                {
                    isEnabledBinding.ConverterParameter = pi.IsEnabledValue;
                    isEnabledBinding.Converter = ValueToBooleanConverter;
                }

                var currentBindingExpression = propertyControl.GetBindingExpression(IsEnabledProperty);
                if (currentBindingExpression != null)
                {
                    var multiBinding = new MultiBinding();
                    multiBinding.Bindings.Add(isEnabledBinding);
                    multiBinding.Bindings.Add(currentBindingExpression.ParentBinding);
                    multiBinding.Converter = AllMultiValueConverter;
                    multiBinding.ConverterParameter = true;
                    propertyControl.SetBinding(IsEnabledProperty, multiBinding);
                }
                else
                {
                    propertyControl.SetBinding(IsEnabledProperty, isEnabledBinding);
                }
            }

            if (pi.IsVisibleDescriptor != null)
            {
                propertyPanel.SetBinding(
                    VisibilityProperty,
                    new Binding(pi.IsVisibleDescriptor.Name) { Converter = BoolToVisibilityConverter });
            }

            if (this.EnableLabelWidthResizing && pi.HeaderPlacement == HeaderPlacement.Left)
            {
                propertyPanel.Children.Add(
                    new GridSplitter
                        {
                            Width = 4,
                            Background = Brushes.Transparent,
                            HorizontalAlignment = HorizontalAlignment.Right,
                            Focusable = false
                        });
            }

            panel.Children.Add(propertyPanel);
        }
示例#25
0
文件: BindingTest.cs 项目: dfr0/moon
		public void DataContext_PreferFrameworkElementParentOverMentor_SetParentToNull ()
		{
			var root1 = new Canvas { DataContext = 1 };
			var root2 = new Canvas { DataContext = 2 };

			var target = new ContentControl ();
			target.SetBinding (FrameworkElement.DataContextProperty, new Binding ());

			// This sets FrameworkElement.Parent
			root1.Children.Add (target);

			// This sets a new Mentor
			ToolTipService.SetPlacementTarget (root2, target);
			CreateAsyncTest (root1,
				() => {
					// We should be using the DataContext from FrameworkElement.Parent, not the mentor
					Assert.AreEqual (1, target.DataContext, "#1");
					root1.Children.Clear ();

					// After clearing the Parent we no longer listen for DataContext changes on the parent
					root1.DataContext = 3;
				}, () => {
					Assert.AreEqual (1, target.DataContext, "#2");

					// We don't listen for the mentor either
					root2.DataContext = 5;
				}, () => {
					Assert.AreEqual (1, target.DataContext, "#3");
				}
			);
		}
 /// <summary>
 /// Creates a content control.
 /// </summary>
 /// <param name="property">The property.</param>
 /// <returns>
 /// A <see cref="ContentControl" />.
 /// </returns>
 protected virtual FrameworkElement CreateContentControl(PropertyItem property)
 {
     var b = new ContentControl
     {
         HorizontalAlignment = HorizontalAlignment.Stretch,
         VerticalAlignment = VerticalAlignment.Center,
         Margin = new Thickness(4),
         Focusable = false,
         HorizontalContentAlignment = HorizontalAlignment.Stretch
     };
     b.SetBinding(ContentControl.ContentProperty, property.CreateBinding());
     return b;
 }
        /// <summary>
        /// Creates the control for a property.
        /// </summary>
        /// <param name="property">
        /// The property item.
        /// </param>
        /// <param name="options">
        /// The options.
        /// </param>
        /// <returns>
        /// A element.
        /// </returns>
        public virtual FrameworkElement CreateControl(PropertyItem property, PropertyControlFactoryOptions options)
        {
            this.UpdateConverter(property);

            foreach (var editor in this.Editors)
            {
                if (editor.IsAssignable(property.Descriptor.PropertyType))
                {
                    var c = new ContentControl
                        {
                            ContentTemplate = editor.EditorTemplate,
                            VerticalAlignment = VerticalAlignment.Center,
                            HorizontalAlignment = HorizontalAlignment.Left
                        };
                    c.SetBinding(FrameworkElement.DataContextProperty, property.CreateOneWayBinding());
                    return c;
                }
            }

            if (property.Is(typeof(bool)))
            {
                return this.CreateBoolControl(property);
            }

            if (property.Is(typeof(Enum)))
            {
                return this.CreateEnumControl(property, options);
            }

            if (property.Is(typeof(Color)))
            {
                return this.CreateColorControl(property);
            }

            if (property.Is(typeof(Brush)))
            {
                return this.CreateBrushControl(property);
            }

            if (property.Is(typeof(FontFamily)))
            {
                return this.CreateFontFamilyControl(property);
            }

            if (property.Is(typeof(ImageSource)) || property.DataTypes.Contains(DataType.ImageUrl))
            {
                return this.CreateImageControl(property);
            }

            if (property.DataTypes.Contains(DataType.Html))
            {
                return this.CreateHtmlControl(property);
            }

            if (property.Is(typeof(Uri)))
            {
                return this.CreateLinkControl(property);
            }

            if (property.ItemsSourceDescriptor != null)
            {
                return this.CreateComboBoxControl(property);
            }

            if (property.Is(typeof(SecureString)))
            {
                return this.CreateSecurePasswordControl(property);
            }

            if (this.UseDatePicker && property.Is(typeof(DateTime)))
            {
                return this.CreateDateTimeControl(property);
            }

            if (property.IsFilePath)
            {
                return this.CreateFilePathControl(property);
            }

            if (property.IsDirectoryPath)
            {
                return this.CreateDirectoryPathControl(property);
            }

            if (property.PreviewFonts)
            {
                return this.CreateFontPreview(property);
            }

            if (property.IsComment)
            {
                return this.CreateCommentControl(property);
            }

            if (property.IsPassword)
            {
                return this.CreatePasswordControl(property);
            }

            if (property.IsSlidable)
            {
                return this.CreateSliderControl(property);
            }

            if (property.IsSpinnable)
            {
                return this.CreateSpinControl(property);
            }

            if (property.Is(typeof(IList)))
            {
                return this.CreateGridControl(property);
            }

            if (property.Is(typeof(IDictionary)))
            {
                return this.CreateDictionaryControl(property);
            }

            return this.CreateDefaultControl(property);
        }
示例#28
0
            private ContentControl GetCurrentContent()
            {
                var item = _tabControl.SelectedItem;
                if (item == null) return null;

                var tabItem = _tabControl.ItemContainerGenerator.ContainerFromItem(item);
                if (tabItem == null) return null;

                var cachedContent = GetInternalCachedContent(tabItem);
                if (cachedContent == null)
                {
                    cachedContent = new ContentControl
                    {
                        DataContext = item,
                        ContentTemplate = GetTemplate(_tabControl),
                        ContentTemplateSelector = GetTemplateSelector(_tabControl)
                    };

                    cachedContent.SetBinding(ContentControl.ContentProperty, new Binding());
                    SetInternalCachedContent(tabItem, cachedContent);
                }

                return cachedContent;
            }
示例#29
0
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string newTemplateName = String.Empty;
            ContextExecutionViewState state = (ContextExecutionViewState)value;
            switch (state)
            {
                case ContextExecutionViewState.Working:
                    newTemplateName = "ExecutableWorkingTemplate";
                    break;
                case ContextExecutionViewState.Initial:
                    newTemplateName = "ExecutableInitialTemplate";
                    break;
                case ContextExecutionViewState.Ready:
                    newTemplateName = "ExecutableReadyTemplate";
                    break;
                default:
                    break;
            }

            if (!String.IsNullOrWhiteSpace(newTemplateName))
            {
                var contentControl = new ContentControl();
                contentControl.ContentTemplate = dictionary[newTemplateName] as DataTemplate;
                contentControl.SetBinding(ContentControl.ContentProperty, new Binding());
                return contentControl;
            }
            else
            {
                return Binding.DoNothing;
            }
        }