Binding only part of a label

前端 未结 6 1776
说谎
说谎 2020-12-14 01:30

How would one achieve mixing bound values with constant text in a WPF bound control?

For example, say I have a form displaying orders, and I want a label that displa

6条回答
  •  臣服心动
    2020-12-14 02:10

    If you're using 3.5 SP1, you can use the StringFormat property on the binding:

    Otherwise, use a converter:

    
    

    With StringFormatConverter being an IValueConverter:

    [ValueConversion(typeof(object), typeof(string))]
    public class StringFormatConverter : IValueConverter
    {
        public string StringFormat { get; set; }
    
        public object Convert(object value, Type targetType,
                              object parameter, CultureInfo culture) {
             if (string.IsNullOrEmpty(StringFormat)) return "";
             return string.Format(StringFormat, value);
        }
    
    
        public object ConvertBack(object value, Type targetType,
                                  object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    

    That'll do the trick.

    [Edit : Change the Text property to Content]

提交回复
热议问题