c# – 带有标记扩展名的字符串格式
我试图使string.Format作为
WPF中的一个方便的函数可用,以便各种文本部分可以在纯XAML中组合,而不需要代码隐藏的样板.主要问题是对函数的参数来自其他嵌套标记扩展(如Binding)的情况的支持.
实际上,有一个非常接近我所需要的功能:MultiBinding.不幸的是,它只能接受绑定,但不能接受其他动态类型的内容,如DynamicResources. 如果我的所有数据源都是绑定的,我可以使用这样的标记: <TextBlock> <TextBlock.Text> <MultiBinding Converter="{StaticResource StringFormatConverter}"> <Binding Path="FormatString"/> <Binding Path="Arg0"/> <Binding Path="Arg1"/> <!-- ... --> </MultiBinding> </TextBlock.Text> </TextBlock> 与StringFormatConveter的明显实现. 我试图实现一个自定义的标记扩展,以便语法是这样的: <TextBlock> <TextBlock.Text> <l:StringFormat Format="{Binding FormatString}"> <DynamicResource ResourceKey="ARG0ID"/> <Binding Path="Arg1"/> <StaticResource ResourceKey="ARG2ID"/> </MultiBinding> </TextBlock.Text> </TextBlock> 或者也许只是 <TextBlock Text="{l:StringFormat {Binding FormatString},arg0={DynamicResource ARG0ID},arg1={Binding Arg2},arg2='literal string',...}"/> 但是,对于参数为另一个标记扩展的情况,我坚持执行ProvideValue(IServiceProvider serviceProvider). 互联网中的大多数示例都是微不足道的:他们根本不使用serviceProvider,或者查询IProvideValueTarget,这主要是说标记扩展的目标是什么依赖属性.在任何情况下,代码都知道在ProvideValue调用时应该提供的值.然而,ProvideValue只会被调用一次(except for templates,这是一个单独的故事),所以如果实际值不是常数,就应该使用另外的策略(就像Binding等). 我在Reflector中查找了Binding的实现,它的ProvideValue方法实际上并没有返回真正的目标对象,而是返回System.Windows.Data.BindingExpression类的一个实例,它似乎做了所有的真正的工作.关于DynamicResource也是一样的:它只是返回一个System.Windows.ResourceReferenceExpression的一个实例,该实例关心订阅(内部)InheritanceContextChanged并在适当时使该值无效.然而,我从代码中看不到什么是以下内容: >如何发生类型BindingExpression / ResourceReferenceExpression的对象不被“按原样”处理,但被要求基础值? 我实际上发现了一个标记扩展库实现,声称支持连接字符串(这完全映射到我的用例)(project,code,concatenation implementation依赖于other code),但似乎只支持库类型的嵌套扩展(即,你不能在里面嵌入一个香草Binding). 有没有办法实现问题顶部提出的语法?这是一个受支持的场景,还是只能从WPF框架内部执行此操作(因为System.Windows.Expression有一个内部构造函数)? 实际上,我使用自定义的不可见助手UI元素来实现所需的语义: <l:FormatHelper x:Name="h1" Format="{DynamicResource FORMAT_ID'"> <l:FormatArgument Value="{Binding Data1}"/> <l:FormatArgument Value="{StaticResource Data2}"/> </l:FormatHelper> <TextBlock Text="{Binding Value,ElementName=h1}"/> (其中FormatHelper跟踪其子项及其依赖属性更新,并将最新结果存储到Value中),但这种语法似乎是丑陋的,我想在视觉树中摆脱帮助项. 最终的目的是为了便于翻译:像15秒直到爆炸一样的UI字符串自然地表示为本地化格式“{0}直到爆炸”(进入ResourceDictionary,当语言改变时将被替换),并绑定到表示时间的VM依赖属性. 更新报告:我尝试使用我可以在互联网上找到的所有信息实现标记扩展.全面实施在这里([1],[2],[3]),这里是核心部分: var result = new MultiBinding() { Converter = new StringFormatConverter(),Mode = BindingMode.OneWay }; foreach (var v in values) { if (v is MarkupExtension) { var b = v as Binding; if (b != null) { result.Bindings.Add(b); continue; } var bb = v as BindingBase; if (bb != null) { targetObjFE.SetBinding(AddBindingTo(targetObjFE,result),bb); continue; } } if (v is System.Windows.Expression) { DynamicResourceExtension mex = null; // didn't find other way to check for dynamic resource try { // rrc is a new ResourceReferenceExpressionConverter(); mex = (MarkupExtension)rrc.ConvertTo(v,typeof(MarkupExtension)) as DynamicResourceExtension; } catch (Exception) { } if (mex != null) { targetObjFE.SetResourceReference( AddBindingTo(targetObjFE,mex.ResourceKey); continue; } } // fallback result.Bindings.Add( new Binding() { Mode = BindingMode.OneWay,Source = v }); } return result.ProvideValue(serviceProvider); 这似乎适用于嵌套绑定和动态资源,但是尝试将其嵌套在本身中可能失败,因为在这种情况下,从IProvideValueTarget获取的targetObj为null.我试图解决这个问题,将嵌套绑定合并到外部绑定([1a],[2a])(添加多绑定溢出到外部绑定),这可能与嵌套的多绑定和格式扩展一起使用,但仍然使用嵌套的动态资源失败. 有趣的是,当嵌套不同种类的标记扩展时,我在外部扩展中获得Bindings和MultiBindings,但ResourceReferenceExpression代替DynamicResourceExtension.我不知道为什么它不一致(和BindingExpression重构的Binding如何). 更新报告:不幸的是,答案中提出的想法并没有解决问题.也许这证明,标记扩展虽然功能强大,功能多样,但需要WPF团队更多的关注. 无论如何,我感谢参加讨论的任何人.所提出的部分解决方案足够复杂,值得更多的提升. 更新报告:似乎没有很好的解决方案与标记扩展,或至少WPF知识需要创建的水平太深,不实际. 然而,@adabyron有一个改进的想法,这有助于隐藏主机项目中的帮助元素(但是这个价格是将主机的子类化).我会尝试看看是否可以摆脱子类化(使用劫持主机的LogicalChildren的行为,并添加帮助器元素到我的脑海中,灵感来自同一答案的旧版本). 解决方法
看看下面是否适合你.我拿了你在评论中提供的
test case,并稍微扩展,以更好地说明机制.我猜关键是通过在嵌套容器中使用DependencyProperties来保持灵活性.
编辑:我已经用TextBlock的子类替换了混合行为.这增加了DataContext和DynamicResources更容易的连接. 在旁注中,您的项目使用DynamicResources引入条件的方式不是我会推荐的.而是尝试使用ViewModel来建立条件和/或使用触发器. XAML: <UserControl x:Class="WpfApplication1.Controls.ExpiryView" xmlns:system="clr-namespace:System;assembly=mscorlib" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:props="clr-namespace:WpfApplication1.Properties" xmlns:models="clr-namespace:WpfApplication1.Models" xmlns:h="clr-namespace:WpfApplication1.Helpers" xmlns:c="clr-namespace:WpfApplication1.CustomControls" Background="#FCF197" FontFamily="Segoe UI" TextOptions.TextFormattingMode="Display"> <!-- please notice the effect of this on font fuzzyness --> <UserControl.DataContext> <models:ExpiryViewModel /> </UserControl.DataContext> <UserControl.Resources> <system:String x:Key="ShortOrLongDateFormat">{0:d}</system:String> </UserControl.Resources> <Grid> <StackPanel> <c:TextBlockComplex VerticalAlignment="Center" HorizontalAlignment="Center"> <c:TextBlockComplex.Content> <h:StringFormatContainer StringFormat="{x:Static props:Resources.ExpiryDate}"> <h:StringFormatContainer.Values> <h:StringFormatContainer Value="{Binding ExpiryDate}" StringFormat="{DynamicResource ShortOrLongDateFormat}" /> <h:StringFormatContainer Value="{Binding SecondsToExpiry}" /> </h:StringFormatContainer.Values> </h:StringFormatContainer> </c:TextBlockComplex.Content> </c:TextBlockComplex> </StackPanel> </Grid> </UserControl> TextBlockComplex: using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Windows; using System.Windows.Controls; using WpfApplication1.Helpers; namespace WpfApplication1.CustomControls { public class TextBlockComplex : TextBlock { // Content public StringFormatContainer Content { get { return (StringFormatContainer)GetValue(ContentProperty); } set { SetValue(ContentProperty,value); } } public static readonly DependencyProperty ContentProperty = DependencyProperty.Register("Content",typeof(StringFormatContainer),typeof(TextBlockComplex),new PropertyMetadata(null)); private static readonly DependencyPropertyDescriptor _dpdValue = DependencyPropertyDescriptor.FromProperty(StringFormatContainer.ValueProperty,typeof(StringFormatContainer)); private static readonly DependencyPropertyDescriptor _dpdValues = DependencyPropertyDescriptor.FromProperty(StringFormatContainer.ValuesProperty,typeof(StringFormatContainer)); private static readonly DependencyPropertyDescriptor _dpdStringFormat = DependencyPropertyDescriptor.FromProperty(StringFormatContainer.StringFormatProperty,typeof(StringFormatContainer)); private static readonly DependencyPropertyDescriptor _dpdContent = DependencyPropertyDescriptor.FromProperty(TextBlockComplex.ContentProperty,typeof(StringFormatContainer)); private EventHandler _valueChangedHandler; private NotifyCollectionChangedEventHandler _valuesChangedHandler; protected override IEnumerator LogicalChildren { get { yield return Content; } } static TextBlockComplex() { // take default style from TextBlock DefaultStyleKeyProperty.OverrideMetadata(typeof(TextBlockComplex),new FrameworkPropertyMetadata(typeof(TextBlock))); } public TextBlockComplex() { _valueChangedHandler = delegate { AddListeners(this.Content); UpdateText(); }; _valuesChangedHandler = delegate { AddListeners(this.Content); UpdateText(); }; this.Loaded += TextBlockComplex_Loaded; } void TextBlockComplex_Loaded(object sender,RoutedEventArgs e) { OnContentChanged(this,EventArgs.Empty); // initial call _dpdContent.AddValueChanged(this,_valueChangedHandler); this.Unloaded += delegate { _dpdContent.RemoveValueChanged(this,_valueChangedHandler); }; } /// <summary> /// Reacts to a new topmost StringFormatContainer /// </summary> private void OnContentChanged(object sender,EventArgs e) { this.AddLogicalChild(this.Content); // inherits DataContext _valueChangedHandler(this,EventArgs.Empty); } /// <summary> /// Updates Text to the Content values /// </summary> private void UpdateText() { this.Text = Content.GetValue() as string; } /// <summary> /// Attaches listeners for changes in the Content tree /// </summary> private void AddListeners(StringFormatContainer cont) { // in case they have been added before RemoveListeners(cont); // listen for changes to values collection cont.CollectionChanged += _valuesChangedHandler; // listen for changes in the bindings of the StringFormatContainer _dpdValue.AddValueChanged(cont,_valueChangedHandler); _dpdValues.AddValueChanged(cont,_valueChangedHandler); _dpdStringFormat.AddValueChanged(cont,_valueChangedHandler); // prevent memory leaks cont.Unloaded += delegate { RemoveListeners(cont); }; foreach (var c in cont.Values) AddListeners(c); // recursive } /// <summary> /// Detaches listeners /// </summary> private void RemoveListeners(StringFormatContainer cont) { cont.CollectionChanged -= _valuesChangedHandler; _dpdValue.RemoveValueChanged(cont,_valueChangedHandler); _dpdValues.RemoveValueChanged(cont,_valueChangedHandler); _dpdStringFormat.RemoveValueChanged(cont,_valueChangedHandler); } } } StringFormatContainer: using System.Linq; using System.Collections; using System.Collections.ObjectModel; using System.Windows; namespace WpfApplication1.Helpers { public class StringFormatContainer : FrameworkElement { // Values private static readonly DependencyPropertyKey ValuesPropertyKey = DependencyProperty.RegisterReadOnly("Values",typeof(ObservableCollection<StringFormatContainer>),new FrameworkPropertyMetadata(new ObservableCollection<StringFormatContainer>())); public static readonly DependencyProperty ValuesProperty = ValuesPropertyKey.DependencyProperty; public ObservableCollection<StringFormatContainer> Values { get { return (ObservableCollection<StringFormatContainer>)GetValue(ValuesProperty); } } // StringFormat public static readonly DependencyProperty StringFormatProperty = DependencyProperty.Register("StringFormat",typeof(string),new PropertyMetadata(default(string))); public string StringFormat { get { return (string)GetValue(StringFormatProperty); } set { SetValue(StringFormatProperty,value); } } // Value public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value",typeof(object),new PropertyMetadata(default(object))); public object Value { get { return (object)GetValue(ValueProperty); } set { SetValue(ValueProperty,value); } } public StringFormatContainer() : base() { SetValue(ValuesPropertyKey,new ObservableCollection<StringFormatContainer>()); this.Values.CollectionChanged += OnValuesChanged; } /// <summary> /// The implementation of LogicalChildren allows for DataContext propagation. /// This way,the DataContext needs only be set on the outermost instance of StringFormatContainer. /// </summary> void OnValuesChanged(object sender,System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { if (e.NewItems != null) { foreach (var value in e.NewItems) AddLogicalChild(value); } if (e.OldItems != null) { foreach (var value in e.OldItems) RemoveLogicalChild(value); } } /// <summary> /// Recursive function to piece together the value from the StringFormatContainer hierarchy /// </summary> public object GetValue() { object value = null; if (this.StringFormat != null) { // convention: if StringFormat is set,Values take precedence over Value if (this.Values.Any()) value = string.Format(this.StringFormat,this.Values.Select(v => (object)v.GetValue()).ToArray()); else if (Value != null) value = string.Format(this.StringFormat,Value); } else { // convention: if StringFormat is not set,Value takes precedence over Values if (Value != null) value = Value; else if (this.Values.Any()) value = string.Join(string.Empty,this.Values); } return value; } protected override IEnumerator LogicalChildren { get { if (Values == null) yield break; foreach (var v in Values) yield return v; } } } } ExpiryViewModel: using System; using System.ComponentModel; namespace WpfApplication1.Models { public class ExpiryViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { if (this.PropertyChanged != null) PropertyChanged(this,new PropertyChangedEventArgs(propertyName)); } private DateTime _expiryDate; public DateTime ExpiryDate { get { return _expiryDate; } set { _expiryDate = value; OnPropertyChanged("ExpiryDate"); } } public int SecondsToExpiry { get { return (int)ExpiryDate.Subtract(DateTime.Now).TotalSeconds; } } public ExpiryViewModel() { this.ExpiryDate = DateTime.Today.AddDays(2.67); var timer = new System.Timers.Timer(1000); timer.Elapsed += (s,e) => OnPropertyChanged("SecondsToExpiry"); timer.Start(); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |