我正在尝试创建一个DependencyObject从Xaml创建的.它 DependencyProperty的类型List<object>定义如下:
public List<object> Map
{
get { return (List<object>)GetValue(MapProperty); }
set { SetValue(MapProperty, value); }
}
// Using a DependencyProperty as the backing store for Map. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MapProperty =
DependencyProperty.Register("Map", typeof(List<object>), typeof(MyConverter), new PropertyMetadata(null));
Run Code Online (Sandbox Code Playgroud)
XAML:
<MyConverter x:Key="myConverter">
<MyConverter.Map>
<TextPair First="App.Blank" Second ="App.BlankViewModel"/>
</MyConverter.Map>
</MyConverter>
Run Code Online (Sandbox Code Playgroud)
我一直在接受Cannot add instance of type 'UwpApp.Xaml.TextPair' to a collection of type 'System.Collections.Generic.List<Object>.什么可能导致此错误?谢谢.
您已定义的类型DependencyProperty用typeof(List<object>).这意味着该属性需要这种类型.既然List<object>不是TextPair我们需要更通用.而不是使用特殊的通用列表类型,只需使用IList类型并添加new List<object>()为默认值.这应该可以解决您的问题.
public IList Map
{
get { return (IList)GetValue(MapProperty); }
set { SetValue(MapProperty, value); }
}
public static readonly DependencyProperty MapProperty =
DependencyProperty.Register("Map", typeof(IList),
typeof(MyConverter), new PropertyMetadata(new List<object>()));
Run Code Online (Sandbox Code Playgroud)
编辑:
看起来UWP的行为与WPF略有不同.要在UWP中运行此代码,您需要使用泛型IList<object>而不是IList属性类型.