Binding as a Resource

前端 未结 2 1184
不思量自难忘°
不思量自难忘° 2020-11-30 12:10

Can I define a Binding as a Resource and then reuse it with different Controls properties?

Example:

Binding:

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 13:03

    Here are two ways to not do exactly what you want:

    1. Using a custom markup extension

    Skipped all nullchecks etc. to keep it short.

    using System;
    using System.Windows;
    using System.Windows.Data;
    using System.Windows.Markup;
    
    public class BindingDefinition
    {
        public PropertyPath Path { get; set; }
    
        public BindingMode Mode { get; set; }
    }
    
    [MarkupExtensionReturnType(typeof(BindingExpression))]
    public class ApplyBindingDefinition : MarkupExtension
    {
        public BindingDefinition Definition { get; set; }
    
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            var binding = new Binding
            {
                Path = this.Definition.Path,
                Mode = this.Definition.Mode
            };
            return binding.ProvideValue(serviceProvider);
        }
    }
    

    
        
    
    
        
            
            
        
    
    

    2. Making the PropertyPath a resource

    May or may not be enough for your needs.

    
        MyProperty
    
    ...
    
    

提交回复
热议问题