[英]Resolve XAML Binding through Code on Windows Phone 8
我有一個轉換器,它為空字符串提供默認值。 顯然您不能向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}}" />
有任何想法嗎?
您應該能夠通過繼承來完成此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));
...
...
現在,我已經通過繼承轉換器並在構造函數中設置本地化字符串來解決了該問題。 但是,我覺得必須有一個更優雅的解決方案來允許我直接使用基本轉換器。
public class WaypointNameConverter : DefaultForNullOrWhiteSpaceStringConverter
{
public WaypointNameConverter()
{
base.Default = Resources.AppResources.Waypoint_NoName;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.