【问题标题】:Resolve XAML Binding through Code on Windows Phone 8通过 Windows Phone 8 上的代码解决 XAML 绑定
【发布时间】:2013-06-18 02:59:12
【问题描述】:

我有一个为空字符串提供默认值的转换器。显然,您无法将绑定添加到 ConverterParameter,因此我向转换器添加了一个属性,而是绑定到该属性。

但是,我为默认属性返回的值是“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}}" />

有什么想法吗?

【问题讨论】:

    标签: c# xaml windows-phone-8 ivalueconverter


    【解决方案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));
    ...
    ...
    

    【讨论】:

    • 感谢编辑,很抱歉它被拒绝了,因为它是一个正确的编辑!
    • 别担心 - 我想我会编辑代码,让其他有同样问题的人生活更轻松;)
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-20
      • 1970-01-01
      • 2014-01-15
      • 2013-12-30
      • 2014-03-30
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多