2013-06-21 37 views
0

我有一个转换器为空字符串提供了默认值。显然,你不能添加一个绑定到ConverterParameter,所以我添加一个属性到转换器,我将它绑定到。解决在Windows Phone上通过代码绑定XAML 8

但是,我回到默认属性的值是一个“System.Windows.Data.Binding”而不是我的值的字符串。

如何在代码中解析此绑定,以便我可以返回我想要的真正本地化的字符串?

这里的(基于答案https://stackoverflow.com/a/15567799/250254)我的转换器类:

public class DefaultForNullOrWhiteSpaceStringConverter : IValueConverter 
{ 
    public object Default { set; get; } 

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     if (!string.IsNullOrWhiteSpace((string)value)) 
     { 
      return value; 
     } 
     else 
     { 
      if (parameter != null) 
      { 
       return parameter; 
      } 
      else 
      { 
       return this.Default; 
      } 
     } 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotSupportedException(); 
    } 

} 

我的XAML:

<phone:PhoneApplicationPage.Resources> 
    <tc:DefaultForNullOrWhiteSpaceStringConverter x:Key="WaypointNameConverter" 
     Default="{Binding Path=LocalizedResources.Waypoint_NoName, Mode=OneTime, Source={StaticResource LocalizedStrings}}" /> 
</phone:PhoneApplicationPage.Resources> 

<TextBlock Text="{Binding Name, Converter={StaticResource WaypointNameConverter}}" /> 

任何想法?

回答

1

您应该能够从DependencyObject继承和改变你的Default财产是一个DependencyProperty做到这一点。

public class DefaultForNullOrWhiteSpaceStringConverter : DependencyObject, IValueConverter 
{ 
    public string DefaultValue 
    { 
     get { return (string)GetValue(DefaultValueProperty); } 
     set { SetValue(DefaultValueProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for DefaultValue. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty DefaultValueProperty = 
     DependencyProperty.Register("DefaultValue", typeof(string), 
     typeof(DefaultForNullOrWhiteSpaceStringConverter), new PropertyMetadata(null)); 
... 
... 
+0

完美 - 谢谢! – Gavin

+0

感谢编辑,对不起,它被拒绝了,因为它是一个正确的编辑! –

+0

不用担心 - 我想编辑代码以使生活更轻松,对于有同样问题的任何人;) – Gavin

0

现在我已经通过继承我的转换器并在构造函数中设置本地化的字符串来解决问题。但是,我觉得必须有一个更优雅的解决方案来解决我的问题,使基础转换器可以直接使用。

public class WaypointNameConverter : DefaultForNullOrWhiteSpaceStringConverter 
{ 
    public WaypointNameConverter() 
    { 
     base.Default = Resources.AppResources.Waypoint_NoName; 
    } 
}