簡體   English   中英

XAML - 樣式中的轉換器

[英]XAML - Converter within Style

我想在樣式中包含 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屬性,我想使用 Converter 顯示它們的格式。

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();
    }
}

嗯,你不能。 在樣式中,您僅使用轉換器將文本設置為某些無效綁定。 稍后您將其設置為靜態文本。

如果要向值添加特定處理並避免代碼重復,請使用附加變量。

另請注意,您實際上正在創建兩個轉換器。 一種是風格,一種是資源。 所以只需從資源中引用一個,不需要再次創建它。

這是附加的屬性示例。

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" />

它可能無法開箱即用,但您可以大致了解。

如果您顯式設置Text屬性,則會覆蓋樣式中的屬性設置器。

Binding而不是Style使用您的轉換器。

Text="{Binding AppName, Converter={StaticResource StringFormatConverterKey}}"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM