6

如果我有标签:

<Label Content="{StaticResource Foo}" />

有没有办法在 xaml 中附加 *?

我正在寻找类似的东西:

<Label Content="{StaticResource Foo, stringformat={0}*" />

我从资源字典中放置控件的内容,因为该应用程序支持多种语言。我想知道是否可以在 xaml 中附加 *,这样我就不必创建一个事件,然后在该事件触发时附加它。

编辑:

在资源字典中,我有:

 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:system="clr-namespace:System;assembly=mscorlib"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                >

     <system:String x:Key="Foo">Name</system:String>

 </ResourceDictionary>

在我的窗口中,我有:(我合并了最后一个字典)

  <Label Content="{StaticResource 'Foo'}" />

并显示名称

我希望标签显示名称* 而不仅仅是名称

也许用一种风格来实现这一点是可能的。

4

2 回答 2

14

有多种方法可以做到:

  1. 使用ContentStringFormat

    <Label Content="{StaticResource Foo}" ContentStringFormat='{}{0}*'/>
    
  2. 使用StringFormat 绑定(它仅适用于字符串属性,这就是您需要使用 aTextBlock作为Label内容的原因)

    <Label>
       <TextBlock 
           Text="{Binding Source={StaticResource Foo}, StringFormat='{}{0}*'}"/>
    </Label>
    
  3. 或者您可以编写一个转换器来附加*
于 2012-04-16T21:30:49.060 回答
1

感谢@nemesv 的回答,这就是我最终得到的结果:

我创建了以下转换器:

using System;
using System.Windows.Data;
using System.Globalization;

namespace PDV.Converters
{
    [ValueConversion(typeof(String), typeof(String))]
    public class RequiredFieldConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value.ToString() + "*";
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var str = value.ToString();
            return str.Substring(0, str.Length - 2);
        }
    }
}

在我的 app.xaml 文件中,我创建了资源

<Application x:Class="PDV.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml"

             xmlns:conv="clr-namespace:PDV.Converters"  <!--  Include the namespace where converter is located-->
             >
    <Application.Resources>
        <ResourceDictionary >
            <conv:RequiredFieldConverter x:Key="RequiredFieldConverter" />
        </ResourceDictionary>
    </Application.Resources>

</Application>

然后在我的应用程序中的任何地方,我都可以将该转换器用作:

    <Label Content="{Binding Source={StaticResource NameField}, Converter={StaticResource RequiredFieldConverter} }" />
于 2012-04-16T22:21:02.473 回答