XAML - 风格内的转换器

时间:2015-06-23 20:28:08

标签: c# wpf xaml windows-phone-8.1

我想在Style中包含一个Converter for TextBlock'Text属性。我有以下代码:

<Page.Resources>
    <converters:StringFormatConverter x:Key="StringFormatConverter" />
    <Style x:Key="StringFormatStyle" TargetType="TextBlock">
        <Setter Property="Text">
            <Setter.Value>
                <Binding>
                    <Binding.Converter>
                        <converters:StringFormatConverter />
                    </Binding.Converter>
                </Binding>
            </Setter.Value>
        </Setter>
    </Style>
</Page.Resources>
...
<TextBlock Text="some text" Style="{StaticResource StringFormatStyle}" />
<TextBlock Text="{Binding AppName}" Style="{StaticResource StringFormatStyle}" />

问题是我的Converter的Convert方法没有被调用。风格被应用(100%肯定)。

转换器未应用于TextBlock的Text属性会出现什么问题?

长话短说:我的ViewModel中有几个double属性,我想用转换器格式化它们。

PS:我的StringFormatConverter看起来像这样:

public class StringFormatConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value == null)
        {
            return null;
        }

        if (parameter == null)
        {
            return value;
        }

        return string.Format((string)parameter, value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

2 个答案:

答案 0 :(得分:1)

嗯,你不能。 在样式中,您将文本设置为仅使用转换器的无效绑定。之后你将它设置为静态文本。

如果要对值添加特定处理并希望避免代码重复,请使用附加变量。

另请注意,您实际上正在创建两个转换器。一个是风格,一个是资源。所以只需从资源中引用一个,不需要再次以样式创建它。

这是附属物样本。

public class TextConv: DependencyObject
{
    public static readonly DependencyProperty TextProperty = 
    DependencyProperty.RegisterAttached(
      "Text",
      typeof(string),
      typeof(TextConv),
      new PropertyMetadata(null, OnValueChanged)
    );
    public static void SetText(UIElement element, string value)
    {
        element.SetValue(TextProperty, value);
    }
    public static string GetText(UIElement element)
    {
        return (string)element.GetValue(TextProperty);
    }
    private static void OnValueChanged(DependencyObject obj,  DependencyPropertyChangedEventArgs args)
   {
       obj.SetValue(TextBlock.TextProperty, args.NewValue.ToString() + "Hello!");
   }
}

在xaml:

<TextBlock local:TextConv.Text="some text" />

它可能不会开箱即用,但你会得到一般的想法。

答案 1 :(得分:0)

如果明确设置Text属性,那将覆盖样式中的属性设置器。

Binding而不是Style

中使用您的转换器
Text="{Binding AppName, Converter={StaticResource StringFormatConverterKey}}"