Vla*_*lad 12 c# wpf markup-extensions
我试图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>
Run Code Online (Sandbox Code Playgroud)
有明显的实施StringFormatConveter.
我尝试实现自定义标记扩展,以便语法如下:
<TextBlock>
<TextBlock.Text>
<l:StringFormat Format="{Binding FormatString}">
<DynamicResource ResourceKey="ARG0ID"/>
<Binding Path="Arg1"/>
<StaticResource ResourceKey="ARG2ID"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)
或者只是
<TextBlock Text="{l:StringFormat {Binding FormatString},
arg0={DynamicResource ARG0ID},
arg1={Binding Arg2},
arg2='literal string', ...}"/>
Run Code Online (Sandbox Code Playgroud)
但我坚持执行,ProvideValue(IServiceProvider serviceProvider)因为参数是另一个标记扩展.
互联网上的大多数例子都是微不足道的:它们要么根本不使用serviceProvider,要么查询IProvideValueTarget,它们(大多数)说什么依赖属性是标记扩展的目标.在任何情况下,代码都知道在ProvideValue呼叫时应该提供的值.但是,ProvideValue只会调用一次(模板除外,这是一个单独的故事),因此如果实际值不是常数(如同Binding等),则应使用另一种策略.
我查找了BindingReflector中的实现,它的ProvideValue方法实际上并不返回真正的目标对象,而是一个System.Windows.Data.BindingExpression类的实例,它似乎完成了所有真正的工作.同样的问题是DynamicResource:它只返回一个实例System.Windows.ResourceReferenceExpression,它关注订阅(内部)InheritanceContextChanged并在适当时使值无效.通过查看代码我无法理解的是:
BindingExpression/ 的对象ResourceReferenceExpression"按原样"处理,但是被要求提供基础值?MultiBindingExpression知道底层绑定的值已经改变,所以它也必须使其值无效?我实际上发现了一个标记扩展库实现,声称支持连接字符串(完全映射到我的用例)(项目,代码,依赖于其他代码的连接实现),但它似乎只支持嵌套扩展库类型(即,你不能在里面嵌入香草).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}"/>
Run Code Online (Sandbox Code Playgroud)
(FormatHelper跟踪其子项及其依赖项属性的更新,并将最新结果存储到其中Value),但这种语法似乎很难看,我想摆脱可视树中的帮助项.
最终的目标是促进翻译:像"15秒直到爆炸"之类的UI字符串自然地表示为可本地化的格式"{0}直到爆炸"(进入a ResourceDictionary并且将在语言改变时被替换)和BindingVM依赖性代表时间的财产.
更新报告:我尝试使用我在互联网上找到的所有信息来实现标记扩展.完全实现在这里([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, result),
mex.ResourceKey);
continue;
}
}
// fallback
result.Bindings.Add(
new Binding() { Mode = BindingMode.OneWay, Source = v });
}
return result.ProvideValue(serviceProvider);
Run Code Online (Sandbox Code Playgroud)
这似乎适用于嵌套绑定和动态资源,但是在尝试将其嵌套在自身中时会失败,就像在这种情况下targetObj获得IProvideValueTarget的那样null.我试图通过将嵌套绑定合并到外部绑定([1a],[2a])(将多绑定溢出添加到外部绑定中)来解决这个问题,这可能适用于嵌套的多绑定和格式扩展,但是仍然会因嵌套而失败动态资源.
有趣的是,当嵌套不同类型的标记扩展时,我在外部扩展中得到Bindings和MultiBindings,而ResourceReferenceExpression不是DynamicResourceExtension.我想知道为什么它不一致(以及如何Binding重建BindingExpression).
更新报告:遗憾的是,答案中提出的想法并未解决问题.也许它证明了标记扩展虽然是功能强大且功能多样的工具,但需要WPF团队更多关注.
无论如何,我感谢任何参与讨论的人.提出的部分解决方案足够复杂,值得更多的赞成.
更新报告:似乎没有标记扩展的好解决方案,或者至少创建一个所需的WPF知识水平太深而不实用.
但是,@ adabyron有一个改进的想法,这有助于隐藏主机项中的辅助元素(但是这样做的价格是主机的子类).我将试着看看是否有可能摆脱子类化(使用劫持主机的LogicalChildren并在其中添加辅助元素的行为,受到相同答案的旧版本的启发).
看看以下内容是否适合您。我采用了您在评论中提供的测试用例,并对其进行了稍微扩展,以更好地说明该机制。我想关键是通过DependencyProperties在嵌套容器中使用来保持灵活性。

编辑:我已用 TextBlock 的子类替换了混合行为。这增加了 DataContext 和 DynamicResources 的更容易的链接。
DynamicResources顺便说一句,我不推荐您的项目用来引入条件的方式。相反,请尝试使用 ViewModel 来建立条件,和/或使用触发器。
XML:
<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>
Run Code Online (Sandbox Code Playgroud)
文本块复合体:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
字符串格式容器:
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>), typeof(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), typeof(StringFormatContainer), 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), typeof(StringFormatContainer), 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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
过期视图模型:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)