将WPF类库迁移到UWP类库后,以下代码引发错误。 PropertyType的DependencyProperty class财产在WPF工作。我试图从UWP和Dependency properties overview在线文章的similar课程的this获得帮助,但有点困惑。
我在这里缺少什么,我怎么能让它工作?
代码段[在方法的第一行发生错误]:
using Windows.UI.Xaml;
using System.Reflection;
using Windows.UI.Xaml.Documents;
using System.ComponentModel;
....
private static void SetPropertyValue(XmlElement xamlElement, DependencyProperty property, string stringValue)
{
TypeConverter typeConverter TypeDescriptor.GetConverter(property.PropertyType);
try
{
object convertedValue = typeConverter.ConvertFromInvariantString(stringValue);
if (convertedValue != null)
{
xamlElement.SetAttribute(property.Name, stringValue);
}
}
catch(Exception)
{
}
}
错误:
'DependencyProperty'不包含'PropertyType'的定义,并且没有可访问的扩展方法'PropertyType'接受类型'DependencyProperty'的第一个参数(你是否缺少using指令或汇编引用?)
安装包的“ALL”快照:
以下是如何在UWP中使用DependencyProperty
的简单示例。
XAML
<Page x:Name="loginPage"
... >
<TextBlock Text="{Binding welcomeText,ElementName=loginPage}"></TextBlock>
C#
using Windows.UI.Xaml;
...
public string welcomeText
{
get { return (string)GetValue(welcomeTextProperty); }
set { SetValue(welcomeTextProperty, value); }
}
// Using a DependencyProperty as the backing store for welcomeText. This enables animation, styling, binding, etc...
public static readonly DependencyProperty welcomeTextProperty =
DependencyProperty.Register("welcomeText", typeof(string), typeof(LoginPage), null);
在上面的例子中,我们将我们在(C#)后面的代码中定义的依赖属性welcomeText
绑定到TextBlock
。
请注意,ElementName=loginPage
是我们在XAML中定义的页面名称。
希望这可以帮助。
编辑1:
根据我从您的代码中可以理解的,您正在尝试获取PropertyType
值以将其转换为其他类型。
对于此要求,您可以执行以下操作:
在下面的示例中,我们有一个自定义值转换器,它将字符串的长度转换为Visibility
,换句话说,根据它接收转换的字符串长度返回Visibility
,同时还检查提供的value
类型是否为string
类型。
XAML
<Page x:Name="loginPage"
xmlns:converters="using:projectName.converters"
... >
<Page.Resources>
<converters:LengthToVisibilityConverter x:Key="lengthToVisibilityKey"></converters:LengthToVisibilityConverter>
</Page.Resources>
...
<TextBlock x:Name="flyoutTxt" Text="{Binding welcomeText,ElementName=loginPage}"></TextBlock>
<TextBlock Text="Has some text" Visibility="{Binding Path=Text,ElementName=flyoutTxt,Converter={StaticResource lengthToVisibilityKey}}"></TextBlock>
在这里,第二个TextBlock
的可见性是基于flyoutTxt
文本的长度。
C#
自定义Converter类将长度转换为可见性:
class LengthToVisibilityConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{ //checking if type of "value" is String and its length
if(value != null && value.GetType() == typeof(string) &&
value.ToString().Length > 0)
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
请注意,上面定义的属性依赖项不需要进行任何更改。