【问题标题】:What is the best way to convert primitive types in XAML UWP?在 XAML UWP 中转换原始类型的最佳方法是什么?
【发布时间】:2016-02-23 02:08:39
【问题描述】:

在WPF、Silverlight 或Windows Phone Silverlight 中,我们有一个很好的方法可以从 XAML 中指定的字符串转换为任何类型。

我们唯一要做的就是从TypeConverter 子类化,然后用TypeConverterAttribure 标记特定的属性或类,指定框架应该使用哪个转换器。

Universal App XAML 完全没有这个功能,最糟糕的是Universal App XAML 的价值转换能力非常有限。

您只能使用bool、int、double、string,仅此而已。如果您创建具有类型为char 或long 的依赖属性的自定义控件,则不能在XAML 中分配这些属性。

例如,编译器说它不能从string 转换为char。 如果您需要在XAML 中为char 之类的类型分配控件的属性,最好的解决方法是什么?

到目前为止,我想出了一个使用{x:Bind Converter={StaticResource PropertyConverter}, ConverterParameter=Value} 的想法,其中基本上在PropertyConverter 的帮助下将值转换为目标属性类型,PropertyConverter 在内部简单地调用Convert.ChangeType。

问题是这种方法不适用于主题目录中的XAMLs,它们基本上是控制模板。它仅适用于用户控件。

在分配XAML 时,有没有更好的方法,最好是通用方法,将任何类型从string 转换为特定类型?

【问题讨论】:

    标签: wpf xaml win-universal-app typeconverter


    【解决方案1】:

    转换器是正确的方法。您不能在主题 xaml 文件中使用 x:Bind 的原因(例如在 datatemplace 中)是它需要不同的设置。您可以使用Binding 代替x:Bind。

    样本:

    Visibility="{Binding IsMenuOpen, Converter={StaticResource BooleanToVisibility}}"
    

    【讨论】:

    • 不幸的是我不能使用绑定。正如我提到的,我转换静态数据。 x:Bind 允许您省略为绑定指定属性名称。如果你这样做是为了绑定它根本不会调用转换器。
    • 使用属性返回静态数据并使用Binding怎么样?
    【解决方案2】:

    看起来从创作者更新开始,您现在可以使用this method 来复制此行为,来自文章:

    namespace CustomControlWithType
    {
        [Windows.Foundation.Metadata.CreateFromString(MethodName = "CustomControlWithType.Location.ConvertToLatLong")]
        public class Location
        {
            public double Latitude { get; set; }
            public double Longitude { get; set; }
            public double Altitude { get; set; }
    
            public static Location ConvertToLatLong(string rawString)
            {
                string[] coords = rawString.Split(',');
    
                var position = new Location();
                position.Latitude = Convert.ToDouble(coords[0]);
                position.Longitude = Convert.ToDouble(coords[1]);
    
                if (coords.Length > 2)
                {
                    position.Altitude = Convert.ToDouble(coords[2]);
                }
    
                return position;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-09
      • 2015-12-24
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多