Почему свойство зависимости с типом XXX может получить значение другого типа?
Является ли тип свойства зависимости, только что определенный для значения по умолчанию?
Например:
Структура проекта:
![Project](https://i.stack.imgur.com/Vrj0A.png)
Код управления пользователем (CarControl):
XAML-код:
<UserControl x:Class="TypeOfDependencyProperty.Controls.CarControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<TextBlock Text="{Binding Brand}"/>
</Grid>
</UserControl>
Код (C#):
using System.Windows;
using System.Windows.Controls;
namespace TypeOfDependencyProperty.Controls
{
public partial class CarControl : UserControl
{
#region Brand
public static readonly DependencyProperty BrandProperty =
DependencyProperty.Register("Brand", typeof(string), typeof(CarControl),
new FrameworkPropertyMetadata((string)string.Empty));
public string Brand
{
get { return (string)GetValue(BrandProperty); }
set { SetValue(BrandProperty, value); }
}
#endregion
public CarControl()
{
InitializeComponent();
}
}
}
Обратите внимание, что это свойство зависимости Brand
имеет тип string
здесь.
Просмотр кода (CarView):
Код XAML:
<Page x:Class="TypeOfDependencyProperty.Views.CarView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="clr-namespace:TypeOfDependencyProperty.Controls"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="CarView">
<Grid>
<controls:CarControl Brand="{Binding Brand}"/>
</Grid>
</Page>
Код позади (C#):
using System.Windows.Controls;
using TypeOfDependencyProperty.ViewModels;
namespace TypeOfDependencyProperty.Views
{
public partial class CarView : Page
{
public CarView()
{
InitializeComponent();
this.DataContext = new CarViewModel();
}
}
}
Просмотр кода модели (CarViewModel):
namespace TypeOfDependencyProperty.ViewModels
{
public class CarViewModel
{
public string Brand { get; set; }
public CarViewModel()
{
Brand = "XXXXXXXXXXXXXXXXXXXXXXXXX"; // Any value
}
}
}
Теперь, если я измените тип с string
на List<XXX>
(или другой), как показано ниже, он продолжает работать.
#region Brand
public static readonly DependencyProperty BrandProperty =
DependencyProperty.Register("Brand", typeof(List<double>), typeof(CarControl),
new FrameworkPropertyMetadata((List<double>)null));
public List<double>Brand
{
get { return (List<double>)GetValue(BrandProperty); }
set { SetValue(BrandProperty, value); }
}
#endregion
Конечно, я получаю следующую ошибку в окне вывода, но она все еще работает! Значение отображается без сбоев при запуске.
System. Windows .Data Ошибка: 1: Невозможно создать конвертер по умолчанию для выполнения односторонних преобразований между типами System.String и 'System.Collections.Generi c .List 1[System.Double]'. Consider using
Converter property of Binding. BindingExpression:Path=Brand;
DataItem='CarViewModel' (HashCode=14000148); target element is
'CarControl' (Name=''); target property is 'Brand' (type 'List
1')
System. Windows .Data Ошибка: 5: значение, созданное BindingExpression, недопустимо для целевого свойства .; Значение = 'Марка автомобиля' BindingExpression: Path = Brand; DataItem = 'CarViewModel' (HashCode = 14000148); целевым элементом является 'CarControl' (Name = ''); целевым свойством является 'Бренд' (тип 'Список`1')
Может кто-нибудь объяснить мне? Это ошибка?