當我嘗試對Rectangle.Child
一個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; }
}
但是,如果我用一個簡單的Dictionary<String, UIElement>
綁定工作正常更換ResourceDictionary
:
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
不起作用。我想這可能會失敗。
當然。我沒有想到這一點。謝謝。 –