当我尝试将ResourceDictionary
项目绑定到 时Rectangle.Child
,出现异常:
ArgumentException: Value does not fall within the expected range.
这是一个例子:
<UserControl.Resources>
<local:PersonConverter x:Key="MyConverter"/>
</UserControl.Resources>
<ListBox ItemsSource="{Binding Persons}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border Child="{Binding Gender, Converter={StaticResource MyConverter}}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
以及背后的代码:
public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
Persons = new List<Person> {new Person("Female"), new Person("Male")};
}
public List<Person> Persons { get; private set; }
}
public class PersonConverter : IValueConverter
{
private ResourceDictionary Items { get; set; }
public PersonConverterRes()
{
Items = new ResourceDictionary
{
{"Male", new Canvas() {
Background = new SolidColorBrush(Colors.Blue),
Height = 100, Width = 100}},
{"Female", new Canvas() {
Background = new SolidColorBrush(Colors.Magenta),
Height = 100, Width = 100}}
};
}
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return Items[value.ToString()];
}
...
}
public class Person
{
public Person(String gender)
{
Gender = gender;
}
public String Gender { get; private set; }
}
但是,如果我用ResourceDictionary
普通替换Dictionary<String, UIElement>
绑定工作正常:
public class PersonConverter : IValueConverter
{
private Dictionary<String, UIElement> Items { get; set; }
public PersonConverterRes()
{
Items = new Dictionary<String, UIElement>
{
{"Male", new Canvas() {
Background = new SolidColorBrush(Colors.Blue),
Height = 100, Width = 100}},
{"Female", new Canvas() {
Background = new SolidColorBrush(Colors.Magenta),
Height = 100, Width = 100}}
};
}
...
}
有谁知道是什么导致了这个异常?
注意:我也在 WinRT 下尝试过。在那里,代码不会引发异常,但如果我使用ResourceDictionary
. 我想它可能会默默地失败。