public static void SetDynamicResourceKey(this DependencyObject obj, DependencyProperty prop, object resourceKey) { var dynamicResource = new DynamicResourceExtension(resourceKey); var resourceReferenceExpression = dynamicResource.ProvideValue(null); obj.SetValue(prop, resourceReferenceExpression); }
public override object ProvideValue(IServiceProvider serviceProvider) { IBinding left; if (Color.TryParse(FrmKey, out var leftColor)) { left = new StaticBinding(leftColor); } else { var lftExt = new DynamicResourceExtension(FrmKey); left = lftExt.ProvideValue(serviceProvider); } IBinding right; if (Color.TryParse(ToKey, out var rightColor)) { right = new StaticBinding(rightColor); } else { var rgtExt = new DynamicResourceExtension(ToKey); right = rgtExt.ProvideValue(serviceProvider); } return(new MultiBinding() { Bindings = new IBinding[] { left, right }, Converter = new DivideConverter(Relate) }); }
object FindResource(object resourceKey) { // NOTE: This code depends on internal implementation details of WPF and // might break in a future release of the platform. Use at your own risk! var resourceReferenceExpression = new DynamicResourceExtension(resourceKey).ProvideValue(null) as Expression; MethodInfo getValue = typeof(Expression).GetMethod( "GetValue", BindingFlags.Instance | BindingFlags.NonPublic); object result = getValue.Invoke( resourceReferenceExpression, new object[] { this, DummyProperty }); // Either we do not have an inheritance context or the // requested resource does not exist, so return null. if (result == DependencyProperty.UnsetValue) { return(null); } // The requested resource was found, so we will receive a // DeferredResourceReference object as a result of calling // GetValue. The only way to resolve that to the actual // resource, without using reflection, is to have a Setter's // Value property unwrap it for us. var deferredResourceReference = result; Setter setter = new Setter(DummyProperty, deferredResourceReference); return(setter.Value); }
public override object ProvideValue(IServiceProvider serviceProvider) { object returnValue = null; try { IProvideValueTarget service = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget)); Binding binding = null; if (this.Path is string) { binding = new Binding { Mode = BindingMode.OneWay }; } else if (this.Path is Binding) { binding = Path as Binding; } else if (this.Path is ImageSource) { return(this.Path); } else if (this.Path is System.Windows.Expression) { ResourceReferenceExpressionConverter cnv = new ResourceReferenceExpressionConverter(); DynamicResourceExtension mex = null; try { mex = (MarkupExtension)cnv.ConvertTo(this.Path, typeof(MarkupExtension)) as DynamicResourceExtension; } catch (Exception) { } if (mex != null) { FrameworkElement targetObject = service.TargetObject as FrameworkElement; if (targetObject == null) { return(Utils.GetEmpty()); } return(targetObject.TryFindResource(mex.ResourceKey as string)); } } else { return(Utils.GetEmpty()); } binding.Converter = new Converter_StringToImageSource(); binding.ConverterParameter = Path is Binding ? null : Path as string; returnValue = binding.ProvideValue(serviceProvider); } catch (Exception) { returnValue = Utils.GetEmpty(); } return(returnValue); }
public override object ProvideValue(IServiceProvider serviceProvider) { var dyExt = new DynamicResourceExtension(ResourceKey); var brush = dyExt.ProvideValue(serviceProvider); return(new MultiBinding() { Bindings = new IBinding[] { brush }, Converter = new MultiplyConverter(Scale) }); }
public override object ProvideValue(IServiceProvider serviceProvider) { var dyExt = new DynamicResourceExtension(BrushName); var brush = dyExt.ProvideValue(serviceProvider); return(new MultiBinding() { Bindings = new IBinding[] { brush }, Converter = new AlphaConverter(Alpha) }); }
protected ViewHandler(Grid viewContainer, CheckConfiguration configuration) { realParentContainer = viewContainer; viewHandlerPrivateView = realParentContainer.FindResource("ViewHandlerPrivateView") as Grid; viewHandlerPrivateView.DisconnectLogicalParent(); realParentContainer.Children.Add(viewHandlerPrivateView); DynamicResourceExtension dre = new DynamicResourceExtension("ViewHandlerPrivateView"); viewContainerForImplementors = GetViewElement <Grid>(viewHandlerPrivateView, "ViewHandlerViewForImplementors"); configurationReference = configuration; }
public override object ProvideValue(IServiceProvider serviceProvider) { var dynamicResource = new DynamicResourceExtension(this.ResourceKey); this.bindingSource = new BindingProxy(dynamicResource.ProvideValue(null)); var dynamicResourceBinding = new Binding { Source = this.bindingSource, Path = new PropertyPath(BindingProxy.ValueProperty), Mode = BindingMode.OneWay }; var targetInfo = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget)); if (targetInfo.TargetObject is DependencyObject dependencyObject) { dynamicResourceBinding.Converter = this.Converter; dynamicResourceBinding.ConverterParameter = this.ConverterParameter; dynamicResourceBinding.ConverterCulture = this.ConverterCulture; dynamicResourceBinding.StringFormat = this.StringFormat; dynamicResourceBinding.TargetNullValue = this.TargetNullValue; if (dependencyObject is FrameworkElement targetFrameworkElement) { targetFrameworkElement.Resources.Add(this.bindingSource, this.bindingSource); } return(dynamicResourceBinding.ProvideValue(serviceProvider)); } var findTargetBinding = new Binding { RelativeSource = new RelativeSource(RelativeSourceMode.Self) }; this.bindingTrigger = new BindingTrigger(); var wrapperBinding = new MultiBinding { Bindings = { dynamicResourceBinding, findTargetBinding, this.bindingTrigger.Binding }, Converter = new InlineMultiConverter(this.WrapperConvert) }; return(wrapperBinding.ProvideValue(serviceProvider)); }
public object ProvideValue(string expression, object obj, IEnumerable <CssNamespace> namespaces) { object parseResult = Parse(expression, (FrameworkElement)obj, namespaces); if (parseResult is Binding binding) { parseResult = binding.ProvideValue(null); } else if (parseResult?.GetType().Name == "ResourceReferenceExpression") { var resourceKey = TypeHelpers.GetPropertyValue(parseResult, "ResourceKey"); parseResult = new DynamicResourceExtension(resourceKey); } return(parseResult); }
public override object ProvideValue(IServiceProvider serviceProvider) { var dyExt = new DynamicResourceExtension(ForegroundName); var brush = dyExt.ProvideValue(serviceProvider); var tag = new Binding(nameof(TextEditor.Tag)) { RelativeSource = new RelativeSource(RelativeSourceMode.Self) }; return(new MultiBinding() { Bindings = new IBinding[] { brush, tag }, Converter = new SyntaxHighlightWrapperConverter() }); }
internal static void TransformNodes(System.Xaml.XamlReader xamlReader, System.Xaml.XamlObjectWriter xamlWriter, bool onlyLoadOneNode, bool skipJournaledProperties, bool shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack <WpfXamlFrame> stack, IStyleConnector styleConnector) { while (xamlReader.Read()) { if (shouldPassLineNumberInfo) { if (xamlLineInfo.LineNumber != 0) { xamlLineInfoConsumer.SetLineInfo(xamlLineInfo.LineNumber, xamlLineInfo.LinePosition); } } switch (xamlReader.NodeType) { case System.Xaml.XamlNodeType.NamespaceDeclaration: xamlWriter.WriteNode(xamlReader); if (stack.Depth == 0 || stack.CurrentFrame.Type != null) { stack.PushScope(); // Need to create an XmlnsDictionary. // Look up stack to see if we have one earlier // If so, use that. Otherwise new a xmlnsDictionary WpfXamlFrame iteratorFrame = stack.CurrentFrame; while (iteratorFrame != null) { if (iteratorFrame.XmlnsDictionary != null) { stack.CurrentFrame.XmlnsDictionary = new XmlnsDictionary(iteratorFrame.XmlnsDictionary); break; } iteratorFrame = (WpfXamlFrame)iteratorFrame.Previous; } if (stack.CurrentFrame.XmlnsDictionary == null) { stack.CurrentFrame.XmlnsDictionary = new XmlnsDictionary(); } } stack.CurrentFrame.XmlnsDictionary.Add(xamlReader.Namespace.Prefix, xamlReader.Namespace.Namespace); break; case System.Xaml.XamlNodeType.StartObject: WriteStartObject(xamlReader, xamlWriter, stack); break; case System.Xaml.XamlNodeType.GetObject: xamlWriter.WriteNode(xamlReader); // If there wasn't a namespace node before this get object, need to pushScope. if (stack.CurrentFrame.Type != null) { stack.PushScope(); } stack.CurrentFrame.Type = stack.PreviousFrame.Property.Type; break; case System.Xaml.XamlNodeType.EndObject: xamlWriter.WriteNode(xamlReader); // Freeze if required if (stack.CurrentFrame.FreezeFreezable) { Freezable freezable = xamlWriter.Result as Freezable; if (freezable != null && freezable.CanFreeze) { freezable.Freeze(); } } DependencyObject dependencyObject = xamlWriter.Result as DependencyObject; if (dependencyObject != null && stack.CurrentFrame.XmlSpace.HasValue) { XmlAttributeProperties.SetXmlSpace(dependencyObject, stack.CurrentFrame.XmlSpace.Value ? "default" : "preserve"); } stack.PopScope(); break; case System.Xaml.XamlNodeType.StartMember: // ObjectWriter should NOT process PresentationOptions:Freeze directive since it is Unknown // The space directive node stream should not be written because it induces object instantiation, // and the Baml2006Reader can produce space directives prematurely. if (!(xamlReader.Member.IsDirective && xamlReader.Member == XamlReaderHelper.Freeze) && xamlReader.Member != XmlSpace.Value && xamlReader.Member != XamlLanguage.Space) { xamlWriter.WriteNode(xamlReader); } stack.CurrentFrame.Property = xamlReader.Member; if (skipJournaledProperties) { if (!stack.CurrentFrame.Property.IsDirective) { System.Windows.Baml2006.WpfXamlMember wpfMember = stack.CurrentFrame.Property as System.Windows.Baml2006.WpfXamlMember; if (wpfMember != null) { DependencyProperty prop = wpfMember.DependencyProperty; if (prop != null) { FrameworkPropertyMetadata metadata = prop.GetMetadata(stack.CurrentFrame.Type.UnderlyingType) as FrameworkPropertyMetadata; if (metadata != null && metadata.Journal == true) { // Ignore the BAML for this member, unless it declares a value that wasn't journaled - namely a binding or a dynamic resource int count = 1; while (xamlReader.Read()) { switch (xamlReader.NodeType) { case System.Xaml.XamlNodeType.StartMember: count++; break; case System.Xaml.XamlNodeType.StartObject: XamlType xamlType = xamlReader.Type; XamlType bindingBaseType = xamlType.SchemaContext.GetXamlType(typeof(BindingBase)); XamlType dynamicResourceType = xamlType.SchemaContext.GetXamlType(typeof(DynamicResourceExtension)); if (count == 1 && (xamlType.CanAssignTo(bindingBaseType) || xamlType.CanAssignTo(dynamicResourceType))) { count = 0; WriteStartObject(xamlReader, xamlWriter, stack); } break; case System.Xaml.XamlNodeType.EndMember: count--; if (count == 0) { xamlWriter.WriteNode(xamlReader); stack.CurrentFrame.Property = null; } break; case System.Xaml.XamlNodeType.Value: DynamicResourceExtension value = xamlReader.Value as DynamicResourceExtension; if (value != null) { WriteValue(xamlReader, xamlWriter, stack, styleConnector); } break; } if (count == 0) { break; } } System.Diagnostics.Debug.Assert(count == 0, "Mismatch StartMember/EndMember"); } } } } } break; case System.Xaml.XamlNodeType.EndMember: WpfXamlFrame currentFrame = stack.CurrentFrame; XamlMember currentProperty = currentFrame.Property; // ObjectWriter should not process PresentationOptions:Freeze directive nodes since it is unknown // The space directive node stream should not be written because it induces object instantiation, // and the Baml2006Reader can produce space directives prematurely. if (!(currentProperty.IsDirective && currentProperty == XamlReaderHelper.Freeze) && currentProperty != XmlSpace.Value && currentProperty != XamlLanguage.Space) { xamlWriter.WriteNode(xamlReader); } currentFrame.Property = null; break; case System.Xaml.XamlNodeType.Value: WriteValue(xamlReader, xamlWriter, stack, styleConnector); break; default: xamlWriter.WriteNode(xamlReader); break; } //Only do this loop for one node if loadAsync if (onlyLoadOneNode) { return; } } }
// Token: 0x0600226B RID: 8811 RVA: 0x000AAF38 File Offset: 0x000A9138 internal static void TransformNodes(XamlReader xamlReader, XamlObjectWriter xamlWriter, bool onlyLoadOneNode, bool skipJournaledProperties, bool shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack <WpfXamlFrame> stack, IStyleConnector styleConnector) { while (xamlReader.Read()) { if (shouldPassLineNumberInfo && xamlLineInfo.LineNumber != 0) { xamlLineInfoConsumer.SetLineInfo(xamlLineInfo.LineNumber, xamlLineInfo.LinePosition); } switch (xamlReader.NodeType) { case XamlNodeType.StartObject: WpfXamlLoader.WriteStartObject(xamlReader, xamlWriter, stack); break; case XamlNodeType.GetObject: xamlWriter.WriteNode(xamlReader); if (stack.CurrentFrame.Type != null) { stack.PushScope(); } stack.CurrentFrame.Type = stack.PreviousFrame.Property.Type; break; case XamlNodeType.EndObject: { xamlWriter.WriteNode(xamlReader); if (stack.CurrentFrame.FreezeFreezable) { Freezable freezable = xamlWriter.Result as Freezable; if (freezable != null && freezable.CanFreeze) { freezable.Freeze(); } } DependencyObject dependencyObject = xamlWriter.Result as DependencyObject; if (dependencyObject != null && stack.CurrentFrame.XmlSpace != null) { XmlAttributeProperties.SetXmlSpace(dependencyObject, stack.CurrentFrame.XmlSpace.Value ? "default" : "preserve"); } stack.PopScope(); break; } case XamlNodeType.StartMember: if ((!xamlReader.Member.IsDirective || !(xamlReader.Member == XamlReaderHelper.Freeze)) && xamlReader.Member != WpfXamlLoader.XmlSpace.Value && xamlReader.Member != XamlLanguage.Space) { xamlWriter.WriteNode(xamlReader); } stack.CurrentFrame.Property = xamlReader.Member; if (skipJournaledProperties && !stack.CurrentFrame.Property.IsDirective) { WpfXamlMember wpfXamlMember = stack.CurrentFrame.Property as WpfXamlMember; if (wpfXamlMember != null) { DependencyProperty dependencyProperty = wpfXamlMember.DependencyProperty; if (dependencyProperty != null) { FrameworkPropertyMetadata frameworkPropertyMetadata = dependencyProperty.GetMetadata(stack.CurrentFrame.Type.UnderlyingType) as FrameworkPropertyMetadata; if (frameworkPropertyMetadata != null && frameworkPropertyMetadata.Journal) { int num = 1; while (xamlReader.Read()) { switch (xamlReader.NodeType) { case XamlNodeType.StartObject: { XamlType type = xamlReader.Type; XamlType xamlType = type.SchemaContext.GetXamlType(typeof(BindingBase)); XamlType xamlType2 = type.SchemaContext.GetXamlType(typeof(DynamicResourceExtension)); if (num == 1 && (type.CanAssignTo(xamlType) || type.CanAssignTo(xamlType2))) { num = 0; WpfXamlLoader.WriteStartObject(xamlReader, xamlWriter, stack); } break; } case XamlNodeType.StartMember: num++; break; case XamlNodeType.EndMember: num--; if (num == 0) { xamlWriter.WriteNode(xamlReader); stack.CurrentFrame.Property = null; } break; case XamlNodeType.Value: { DynamicResourceExtension dynamicResourceExtension = xamlReader.Value as DynamicResourceExtension; if (dynamicResourceExtension != null) { WpfXamlLoader.WriteValue(xamlReader, xamlWriter, stack, styleConnector); } break; } } if (num == 0) { break; } } } } } } break; case XamlNodeType.EndMember: { WpfXamlFrame currentFrame = stack.CurrentFrame; XamlMember property = currentFrame.Property; if ((!property.IsDirective || !(property == XamlReaderHelper.Freeze)) && property != WpfXamlLoader.XmlSpace.Value && property != XamlLanguage.Space) { xamlWriter.WriteNode(xamlReader); } currentFrame.Property = null; break; } case XamlNodeType.Value: WpfXamlLoader.WriteValue(xamlReader, xamlWriter, stack, styleConnector); break; case XamlNodeType.NamespaceDeclaration: xamlWriter.WriteNode(xamlReader); if (stack.Depth == 0 || stack.CurrentFrame.Type != null) { stack.PushScope(); for (WpfXamlFrame wpfXamlFrame = stack.CurrentFrame; wpfXamlFrame != null; wpfXamlFrame = (WpfXamlFrame)wpfXamlFrame.Previous) { if (wpfXamlFrame.XmlnsDictionary != null) { stack.CurrentFrame.XmlnsDictionary = new XmlnsDictionary(wpfXamlFrame.XmlnsDictionary); break; } } if (stack.CurrentFrame.XmlnsDictionary == null) { stack.CurrentFrame.XmlnsDictionary = new XmlnsDictionary(); } } stack.CurrentFrame.XmlnsDictionary.Add(xamlReader.Namespace.Prefix, xamlReader.Namespace.Namespace); break; default: xamlWriter.WriteNode(xamlReader); break; } if (onlyLoadOneNode) { return; } } }
void MasterSelectorComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { ComboBox cb = sender as ComboBox; if ((cb == null) || (baseFrameworkElement == null)) { return; } string listItemStyleKey = "SmallMasterListItem"; switch (cb.SelectedIndex) { case 0: break; case 1: listItemStyleKey = "MediumMasterListItem"; break; case 2: listItemStyleKey = "LargeMasterListItem"; break; } // TODO(crhodes): This might be where we need to switch to use a diffrent template style for the list. // Instead of searching from Application, perhaps we can search more locally. The sender may be able // to tell us where we are. //Style listItemStyle = System.Windows.Application.Current.FindResource(listItemStyleKey) as Style; Style listItemStyle = baseFrameworkElement.FindResource(listItemStyleKey) as Style; foreach (System.Windows.Trigger t in listItemStyle.Triggers) { //Common.WriteToDebugWindow(string.Format("Trigger type:{0} value:{1} IsSealed:{2}", t.GetType(), t.DependencyObjectType, t.IsSealed)); foreach (System.Windows.Setter s in t.Setters) { //Common.WriteToDebugWindow(string.Format(" Setter Property.Name:{0} value:{1}", s.Property.Name, s.Value)); } } DynamicResourceExtension dr = new DynamicResourceExtension(); var tmplt = System.Windows.Application.Current.FindResource("smallServerDetailsTemplateSelected"); dr.ResourceKey = tmplt; //((Setter)((Trigger)listItemStyle.Triggers[0]).Setters[0]) //((Setter)((Trigger)listItemStyle.Triggers[0]).Setters[0]).Value = tmplt; //listItemStyle.Triggers.IndexOf(); if (listItemStyle != null) { ListBox lb = (ListBox)baseFrameworkElement.FindName("MasterList"); if (lb != null) { lb.ItemContainerStyle = listItemStyle; } } }
public void Destroy() { resExtension = null; tlog.Info(tag, "Destroy() is called!"); }
public void Init() { tlog.Info(tag, "Init() is called!"); resExtension = new DynamicResourceExtension(); }
public void Destroy() { d1 = null; tlog.Info(tag, "Destroy() is called!"); }
// (property, markup extension, value) including the well known WPF TemplateBinding, StaticResource or DynamicResource markup extensions // Writes out a property with a markup extension. However, if there is a x:Static, Type, or TemplateBinding inside the ME, we code that // specially. e.g. Property="{FooExtension {x:Static f:Foo.Bar}}" would be written out as one Baml Record private void Process_PropertyWithExtension() { Common_Process_Property(); short propertyId = _binaryReader.ReadInt16(); Int16 extensionId = _binaryReader.ReadInt16(); Int16 valueId = _binaryReader.ReadInt16(); XamlMember property = GetProperty(propertyId, _context.CurrentFrame.XamlType); Int16 extensionTypeId = (Int16)(extensionId & ExtensionIdMask); XamlType extensionType = BamlSchemaContext.GetXamlType((short)(-extensionTypeId)); bool isValueTypeExtension = (extensionId & TypeExtensionValueMask) == TypeExtensionValueMask; bool isValueStaticExtension = (extensionId & StaticExtensionValueMask) == StaticExtensionValueMask; Type typeExtensionType = null; Type memberType = null; object value = null; // Write out the main Extension {FooExtension _xamlNodesWriter.WriteStartMember(property); // If we're in the binary case, we try to write the value out directly bool handled = false; if (_isBinaryProvider) { object param = null; object providedValue = null; if (isValueStaticExtension) { Type ownerType = null; string staticExParam = GetStaticExtensionValue(valueId, out ownerType, out providedValue); // If it's a Known command or a SystemResourceKey, send the value across directly if (providedValue != null) { param = providedValue; } else { System.Windows.Markup.StaticExtension staticExtension = new System.Windows.Markup.StaticExtension(staticExParam); Debug.Assert(ownerType != null); staticExtension.MemberType = ownerType; param = staticExtension.ProvideValue(null); // if MemberType is set we don't need ITypeResolver } } else if (isValueTypeExtension) { param = BamlSchemaContext.GetXamlType(valueId).UnderlyingType; } else { // For all other scenarios, we want to just write out the type if (extensionTypeId == Baml2006SchemaContext.TemplateBindingTypeId) { param = _context.SchemaContext.GetDependencyProperty(valueId); } else if (extensionTypeId == Baml2006SchemaContext.StaticExtensionTypeId) { param = GetStaticExtensionValue(valueId, out memberType, out providedValue); } else if (extensionTypeId == Baml2006SchemaContext.TypeExtensionTypeId) { param = BamlSchemaContext.GetXamlType(valueId).UnderlyingType; } else { param = BamlSchemaContext.GetString(valueId); } } // Doing == comparison since we only know how to create those quickly here if (extensionTypeId == Baml2006SchemaContext.DynamicResourceTypeId) { value = new DynamicResourceExtension(param); handled = true; } else if (extensionTypeId == Baml2006SchemaContext.StaticResourceTypeId) { value = new StaticResourceExtension(param); handled = true; } else if (extensionTypeId == Baml2006SchemaContext.TemplateBindingTypeId) { value = new TemplateBindingExtension((DependencyProperty)param); handled = true; } else if (extensionTypeId == Baml2006SchemaContext.TypeExtensionTypeId) { value = param; handled = true; } else if (extensionTypeId == Baml2006SchemaContext.StaticExtensionTypeId) { if (providedValue != null) { value = providedValue; } else { System.Windows.Markup.StaticExtension staticExtension = new System.Windows.Markup.StaticExtension((string)param); staticExtension.MemberType = memberType; value = staticExtension; } handled = true; } if (handled) { _xamlNodesWriter.WriteValue(value); _xamlNodesWriter.WriteEndMember(); return; } } if (!handled) { _xamlNodesWriter.WriteStartObject(extensionType); _xamlNodesWriter.WriteStartMember(XamlLanguage.PositionalParameters); if (isValueStaticExtension) { Type ownerType = null; object providedValue; value = GetStaticExtensionValue(valueId, out ownerType, out providedValue); // If it's a Known command or a SystemResourceKey, send the value across directly if (providedValue != null) { _xamlNodesWriter.WriteValue(providedValue); } else { // Special case for {x:Static ...} inside the main extension _xamlNodesWriter.WriteStartObject(XamlLanguage.Static); _xamlNodesWriter.WriteStartMember(XamlLanguage.PositionalParameters); _xamlNodesWriter.WriteValue(value); _xamlNodesWriter.WriteEndMember(); // In BAML scenario, we want to pass MemberType directly along cuz it's optimal if (ownerType != null) { _xamlNodesWriter.WriteStartMember(BamlSchemaContext.StaticExtensionMemberTypeProperty); _xamlNodesWriter.WriteValue(ownerType); _xamlNodesWriter.WriteEndMember(); } _xamlNodesWriter.WriteEndObject(); } } else if (isValueTypeExtension) { // Special case for {x:Type ...} inside the main extension _xamlNodesWriter.WriteStartObject(XamlLanguage.Type); _xamlNodesWriter.WriteStartMember(BamlSchemaContext.TypeExtensionTypeProperty); typeExtensionType = BamlSchemaContext.GetXamlType(valueId).UnderlyingType; if (_isBinaryProvider) { _xamlNodesWriter.WriteValue(typeExtensionType); } else { _xamlNodesWriter.WriteValue(Logic_GetFullyQualifiedNameForType(BamlSchemaContext.GetXamlType(valueId))); } _xamlNodesWriter.WriteEndMember(); _xamlNodesWriter.WriteEndObject(); } else { // For all other scenarios, we want to just write out the type if (extensionTypeId == Baml2006SchemaContext.TemplateBindingTypeId) { if (this._isBinaryProvider) { value = BitConverter.GetBytes(valueId); } else { value = Logic_GetFullyQualifiedNameForMember(valueId); } } else if (extensionTypeId == Baml2006SchemaContext.StaticExtensionTypeId) { // If we're here, that means we're not a binary provider which means we can't // support writing the provided value out directly. object providedValue; value = GetStaticExtensionValue(valueId, out memberType, out providedValue); } else if (extensionTypeId == Baml2006SchemaContext.TypeExtensionTypeId) { value = BamlSchemaContext.GetXamlType(valueId).UnderlyingType; } else { value = BamlSchemaContext.GetString(valueId); } _xamlNodesWriter.WriteValue(value); } _xamlNodesWriter.WriteEndMember(); if (memberType != null) { _xamlNodesWriter.WriteStartMember(BamlSchemaContext.StaticExtensionMemberTypeProperty); _xamlNodesWriter.WriteValue(memberType); _xamlNodesWriter.WriteEndMember(); } } _xamlNodesWriter.WriteEndObject(); _xamlNodesWriter.WriteEndMember(); }
/// <summary> /// Generates the specified parent class. /// </summary> /// <param name="parentClass">The parent class.</param> /// <param name="method">The method.</param> /// <param name="value">The value.</param> /// <param name="baseName">Name of the base.</param> /// <param name="dictionary">The dictionary.</param> /// <returns></returns> public CodeExpression Generate(CodeTypeDeclaration parentClass, CodeMemberMethod method, object value, string baseName, ResourceDictionary dictionary = null) { DynamicResourceExtension dynamicResource = value as DynamicResourceExtension; return(new CodeObjectCreateExpression("ResourceReferenceExpression", new CodePrimitiveExpression(dynamicResource.ResourceKey))); }
public override object?ProvideValue(IServiceProvider serviceProvider) { // Get the binding source for all targets affected by this MarkupExtension // whether set directly on an element or object, or when applied via a style var dynamicResource = new DynamicResourceExtension(ResourceKey); _bindingSource = new BindingProxy(dynamicResource.ProvideValue(null)); // Pass 'null' here // Set up the binding using the just-created source // Note, we don't yet set the Converter, ConverterParameter, StringFormat // or TargetNullValue (More on that below) var dynamicResourceBinding = new Binding() { Source = _bindingSource, Path = new PropertyPath(BindingProxy.ValueProperty), Mode = BindingMode.OneWay }; // Get the TargetInfo for this markup extension var targetInfo = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget)); // Check if this is a DependencyObject. If so, we can set up everything right here. if (targetInfo.TargetObject is DependencyObject dependencyObject) { // Ok, since we're being applied directly on a DependencyObject, we can // go ahead and set all those missing properties on the binding now. dynamicResourceBinding.Converter = Converter; dynamicResourceBinding.ConverterParameter = ConverterParameter; dynamicResourceBinding.ConverterCulture = ConverterCulture; dynamicResourceBinding.StringFormat = StringFormat; dynamicResourceBinding.TargetNullValue = TargetNullValue; // If the DependencyObject is a FrameworkElement, then we also add the // bindingSource to its Resources collection to ensure proper resource lookup if (dependencyObject is FrameworkElement targetFrameworkElement) { targetFrameworkElement.Resources.Add(_bindingSource, _bindingSource); } // And now we simply return the same value as if we were a true binding ourselves return(dynamicResourceBinding.ProvideValue(serviceProvider)); } // Ok, we're not being set directly on a DependencyObject (most likely we're being set via a style) // so we need to get the ultimate target of the binding. // We do this by setting up a wrapper MultiBinding, where we add the above binding // as well as a second binding which we create using a RelativeResource of 'Self' to get the target, // and finally, since we have no way of getting the BindingExpressions (as there will be one wherever // the style is applied), we create a third child binding which is a convenience object on which we // trigger a change notification, thus refreshing the binding. var findTargetBinding = new Binding() { RelativeSource = new RelativeSource(RelativeSourceMode.Self) }; _bindingTrigger = new BindingTrigger(); var wrapperBinding = new MultiBinding() { Bindings = { dynamicResourceBinding, findTargetBinding, _bindingTrigger.Binding }, Converter = new InlineMultiConverter(WrapperConvert) }; return(wrapperBinding.ProvideValue(serviceProvider)); }
public static bool SetValue(object target, IProperty propertyKey, object value) { if (!InstanceBuilderOperations.IsSupported((IMember)propertyKey)) { return(false); } if (DesignTimeProperties.InlineXmlProperty.Equals((object)propertyKey)) { IXmlSerializable serializable = target as IXmlSerializable; if (serializable == null) { return(false); } InstanceBuilderOperations.SetXmlContent(serializable, (string)value); return(true); } DocumentCompositeNode documentCompositeNode = target as DocumentCompositeNode; if (documentCompositeNode != null) { IProperty property = (IProperty)propertyKey.Clone(documentCompositeNode.TypeResolver); documentCompositeNode.Properties[(IPropertyId)property] = (DocumentNode)value; return(true); } ReferenceStep referenceStep = propertyKey as ReferenceStep; if (referenceStep != null) { object obj = value; MarkupExtension markupExtension; if ((markupExtension = obj as MarkupExtension) != null) { if (markupExtension is TemplateBindingExtension) { throw new InstanceBuilderException(ExceptionStringTable.InvalidTemplateBindingInstanceBuilderException); } DependencyPropertyReferenceStep propertyReferenceStep1; object property; if ((propertyReferenceStep1 = referenceStep as DependencyPropertyReferenceStep) != null) { property = propertyReferenceStep1.DependencyProperty; } else { ClrPropertyReferenceStep propertyReferenceStep2; if ((propertyReferenceStep2 = referenceStep as ClrPropertyReferenceStep) == null) { return(false); } property = (object)propertyReferenceStep2.PropertyInfo; } DynamicResourceExtension resourceExtension = markupExtension as DynamicResourceExtension; FrameworkElement frameworkElement = target as FrameworkElement; FrameworkContentElement frameworkContentElement = target as FrameworkContentElement; if (resourceExtension != null && resourceExtension.ResourceKey != null && propertyReferenceStep1 != null && (frameworkElement != null || frameworkContentElement != null)) { if (frameworkElement != null) { propertyReferenceStep1.SetResourceReference((object)frameworkElement, resourceExtension.ResourceKey); } else if (frameworkContentElement != null) { propertyReferenceStep1.SetResourceReference((object)frameworkContentElement, resourceExtension.ResourceKey); } } else { if (Microsoft.Expression.DesignModel.Metadata.KnownProperties.SetterValueProperty.Equals((object)referenceStep)) { referenceStep.SetValue(target, obj); return(true); } bool flag = false; try { obj = markupExtension.ProvideValue((IServiceProvider) new InstanceBuilderOperations.InstanceBuilderServiceProvider(target, property, (IMetadataResolver)referenceStep.DeclaringType.PlatformMetadata)); flag = true; } catch (InvalidOperationException ex) { } if (flag) { if (!(obj is MarkupExtension)) { return(InstanceBuilderOperations.SetValue(target, (IProperty)referenceStep, obj)); } referenceStep.SetValue(target, obj); return(true); } } } else { //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx //if (obj is Expression) //{ // referenceStep.SetValue(target, obj); // return true; //} if (obj != null) { bool flag = false; DependencyPropertyReferenceStep propertyReferenceStep = referenceStep as DependencyPropertyReferenceStep; if (propertyReferenceStep != null) { ITypeId type = (ITypeId)propertyReferenceStep.PlatformTypes.GetType(obj.GetType()); if (PlatformTypes.Binding.IsAssignableFrom(type)) { flag = true; } } if (flag) { propertyReferenceStep.SetBinding(target, value); return(true); } if (!PlatformTypeHelper.GetPropertyType((IProperty)referenceStep).IsInstanceOfType(obj)) { return(false); } } referenceStep.SetValue(target, obj); return(true); } } return(false); }
public void AfterContentIsSet() { Button button = new Button(); button.Content = ""; Assert.IsNull(button.TemplatedParent, "button.TemplatedParent"); #region Background Assert.IsInstanceOfType(typeof(LinearGradientBrush), button.Background); LinearGradientBrush background_linear_gradient_brush = (LinearGradientBrush)button.Background; Assert.AreEqual(background_linear_gradient_brush.StartPoint, new Point(0.5, 0), "background_linear_gradient_brush.StartPoint"); Assert.AreEqual(background_linear_gradient_brush.EndPoint, new Point(0.5, 1), "background_linear_gradient_brush.EndPoint"); Assert.AreEqual(background_linear_gradient_brush.GradientStops.Count, 2, "background_linear_gradient_brush.GradientStops.Count"); #region GradientStop 0 GradientStop gradient_stop0 = background_linear_gradient_brush.GradientStops [0]; Assert.AreEqual(gradient_stop0.Color, Colors.White, "gradient_stop0.Color"); Assert.AreEqual(gradient_stop0.Offset, 0, "gradient_stop0.Offset"); #endregion #region GradientStop 1 GradientStop gradient_stop1 = background_linear_gradient_brush.GradientStops [1]; Assert.AreEqual(gradient_stop1.Color, Color.FromArgb(0xFF, 0xF0, 0xF0, 0xEA), "gradient_stop1.Color"); Assert.AreEqual(gradient_stop1.Offset, 0.9, "gradient_stop1.Offset"); #endregion #endregion #region BorderBrush Assert.IsInstanceOfType(typeof(SolidColorBrush), button.BorderBrush, "button.BorderBrush Type"); SolidColorBrush border_brush = (SolidColorBrush)button.BorderBrush; Assert.AreEqual(border_brush.Color, Color.FromArgb(0xFF, 0x00, 0x3C, 0x74), "border_brush.Color"); #endregion #region Template ControlTemplate template = button.Template; Assert.IsInstanceOfType(typeof(ControlTemplate), template, "template Type"); Assert.AreEqual(template.TargetType, typeof(ButtonBase), "template.TargetType"); Assert.AreEqual(template.Resources.Count, 0, "template.Resources.Count"); Assert.AreEqual(template.Triggers.Count, 3, "template.Triggers.Count"); #region Trigger 0 Assert.IsInstanceOfType(typeof(Trigger), template.Triggers [0], "template.Triggers[0] Type"); Trigger trigger0 = (Trigger)button.Template.Triggers [0]; Assert.AreEqual(trigger0.Property, UIElement.IsKeyboardFocusedProperty, "trigger0.Property"); Assert.AreEqual(trigger0.Value, true, "trigger0.Value"); Assert.AreEqual(trigger0.Setters.Count, 1, "trigger0.Setters.Count"); #region Setter 0 Assert.IsInstanceOfType(typeof(Setter), trigger0.Setters [0], "trigger0.Setters[0] Type"); Setter setter_0_0 = (Setter)trigger0.Setters [0]; #if !Implementation //FIXME: I don't understand why this fails. See the VeryStrangeThing test. Assert.IsTrue(setter_0_0.Property.OwnerType == typeof(ButtonChrome), "setter_0_0.Property.OwnerType 1"); Assert.AreEqual(setter_0_0.Property.OwnerType, typeof(ButtonChrome), "setter_0_0.Property.OwnerType"); Assert.AreEqual(setter_0_0.Property, ButtonChrome.RenderDefaultedProperty, "setter_0_0.Property"); #endif Assert.AreEqual(setter_0_0.TargetName, "Chrome", "setter_0_0.TargetName"); Assert.AreEqual(setter_0_0.Value, true, "setter_0_0.Value"); #endregion #endregion #region Trigger 1 Assert.IsInstanceOfType(typeof(Trigger), template.Triggers [1], "template.Triggers[1] Type"); Trigger trigger1 = (Trigger)button.Template.Triggers [1]; Assert.AreEqual(trigger1.Property, ToggleButton.IsCheckedProperty, "trigger1.Property"); Assert.AreEqual(trigger1.Value, true, "trigger1.Value"); Assert.AreEqual(trigger1.Setters.Count, 1, "trigger1.Setters.Count"); #region Setter 0 Assert.IsInstanceOfType(typeof(Setter), trigger1.Setters [0], "trigger1.Setters[0] Type"); Setter setter_1_0 = (Setter)trigger1.Setters [0]; #if !Implementation //FIXME: Probably the same thing Assert.AreEqual(setter_1_0.Property, ButtonChrome.RenderPressedProperty, "setter_1_0.Property"); #endif Assert.AreEqual(setter_1_0.TargetName, "Chrome", "setter_1_0.TargetName"); Assert.AreEqual(setter_1_0.Value, true, "setter_1_0.Value"); #endregion #endregion #region Trigger 2 Assert.IsInstanceOfType(typeof(Trigger), template.Triggers [2], "template.Triggers[2] Type"); Trigger trigger2 = (Trigger)button.Template.Triggers [2]; Assert.AreEqual(trigger2.Property, UIElement.IsEnabledProperty, "trigger2.Property"); Assert.AreEqual(trigger2.Value, false, "trigger2.Value"); Assert.AreEqual(trigger2.Setters.Count, 1, "trigger2.Setters.Count"); #region Setter 0 Assert.IsInstanceOfType(typeof(Setter), trigger2.Setters [0], "trigger2.Setters[0] Type"); Setter setter_2_0 = (Setter)trigger2.Setters [0]; Assert.AreEqual(setter_2_0.Property, TextElement.ForegroundProperty, "setter_2_0.Property"); Assert.AreEqual(setter_2_0.TargetName, null, "setter_2_0.TargetName"); Assert.IsInstanceOfType(typeof(DynamicResourceExtension), setter_2_0.Value, "setter_2_0.Value Type"); DynamicResourceExtension settter_2_0DynamicResourceExtension = (DynamicResourceExtension)setter_2_0.Value; Assert.AreEqual(settter_2_0DynamicResourceExtension.ResourceKey.ToString(), "GrayTextBrush"); #endregion #endregion #endregion #region Alignment Assert.AreEqual(button.HorizontalAlignment, HorizontalAlignment.Stretch, "button.HorizontalAlignment"); Assert.AreEqual(button.VerticalAlignment, VerticalAlignment.Stretch, "button.VerticalAlignment"); Assert.AreEqual(button.HorizontalContentAlignment, HorizontalAlignment.Center, "button.HorizontalContentAlignment"); Assert.AreEqual(button.VerticalContentAlignment, VerticalAlignment.Center, "button.VerticalContentAlignment"); #endregion Assert.IsNull(button.Template.VisualTree, "button.Template.VisualTree"); }
/// <summary> /// Provides a values to be used by the framework to set a given target's object target property binding. /// </summary> /// <param name="serviceProvider">Service provider offered by the framework.</param> /// <returns>A <see cref="Binding"/> for the targeted object and property.</returns> public override object ProvideValue(IServiceProvider serviceProvider) { // Build context: var pvt = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget; var targetObject = pvt?.TargetObject != null ? pvt.TargetObject as DependencyObject : null; if (pvt?.TargetObject?.GetType().Name == "SharedDp") { return(pvt.TargetObject); // template usage, see https://stackoverflow.com/questions/26877676/how-do-i-get-a-bindingexpression-from-a-binding-object. } // In source of BindingBase classes, we should return the current instance (so this extension) as a result // when encountering a CLR property. However, framework would allow only BindingBase derivatives as a result, // and we cannot functionnaly derive from them (sealed + internal dependencies). // Thus, throw exceptions to prevent developpers from using this extension in some specific cases: if (pvt?.TargetObject is SetterBase) // we cannot get target for a CLI setter object { throw new NotSupportedException(nameof(SingleBindingExtension) + " cannot be used with a " + nameof(SetterBase) + "."); } else if (pvt?.TargetObject is TriggerBase) // same for triggers { throw new NotSupportedException(nameof(SingleBindingExtension) + " cannot be used with a " + nameof(TriggerBase) + "."); } else if (pvt?.TargetObject is Condition) // same for datatrigger conditions { throw new NotSupportedException(nameof(SingleBindingExtension) + " cannot be used with a " + nameof(Condition) + "."); } var solvedTarget = pvt?.TargetObject ?? null; if (solvedTarget == null || !(solvedTarget is DependencyObject)) { // Try to reach root element in xaml namescope to later setup our dynamic resource: if (serviceProvider.GetService(typeof(IRootObjectProvider)) is IRootObjectProvider xnr) { solvedTarget = xnr.RootObject; } } // Build what will be our proxy binder: var dynamicResource = new DynamicResourceExtension(ResourceKey); ProxyBinder = new BindingProxy(dynamicResource.ProvideValue(null)); // Override base properties to setup the proxy binder as source: base.Source = ProxyBinder; base.Path = new PropertyPath(BindingProxy.DataProperty); base.Mode = BindingMode.OneWay; // Let base create binding then return result: var result = base.ProvideValue(serviceProvider); // Now our binding proxy must be set in the resource dictionary of our // target object to be in its scope: // Check if binding source was not resolved, in which case postpone processing // when target element is loaded: if (solvedTarget is FrameworkElement solvedTargetAsFE) { if (!solvedTargetAsFE.IsLoaded) { solvedTargetAsFE.Loaded += Target_Loaded; } else if (!solvedTargetAsFE.Resources.Contains(ProxyBinder)) { solvedTargetAsFE.Resources[ProxyBinder] = ProxyBinder; } } return(result); // return the result. }