Я создаю приложение UWP, используя шаблон 10 и MVVM. Мое требование состоит в том, чтобы создать UserControl, который будет иметь свои собственные свойства зависимостей, а также собственную ViewModel.
Мое требование:
- Вызовите команду Parent ViewModel при нажатии кнопки.
- Привязать текст TexBlock из UserControl ViewModel
Мой пользовательский контроль выглядит так:
<vm:MyUserControl1 AddItem="{Binding MyCommand}" Component="{Binding}" RelativePanel.Below="abc" />
Пользовательский контроль XAML:
<StackPanel>
<TextBlock Text="{x:Bind Component.Text, Mode=OneWay}"/>
<Button x:Name="Button" Content="Click Me" Command="{x:Bind AddItem}">
</Button>
</StackPanel>
Это код UserControl за кодом:
public sealed partial class MyUserControl1 : UserControl
{
public MyUserControl1()
{
this.InitializeComponent();
// mygrid.DataContext = this;
(this.Content as FrameworkElement).DataContext = this;
}
public static readonly DependencyProperty AddItemProperty =
DependencyProperty.Register(
"AddItem",
typeof(ICommand),
typeof(MyUserControl1), new PropertyMetadata(null));
public ICommand AddItem
{
get { return (ICommand)GetValue(AddItemProperty); }
set { SetValue(AddItemProperty, value); }
}
public static readonly DependencyProperty ComponentProperty = DependencyProperty.Register("Component",typeof(MyViewModel),typeof(MyUserControl1),new PropertyMetadata(null));
public MyViewModel Component
{
get { return (MyViewModel)GetValue(ComponentProperty); }
set { SetValue(ComponentProperty, value); }
}
}
Модель просмотра пользовательского контроля:
public class MyViewModel:ViewModelBase
{
public MyViewModel()
{
}
public string Text => "ABC";
}
Модель родительского просмотра:
public class SettingsPartViewModel : ViewModelBase
{
DelegateCommand _MyCommand;
public DelegateCommand MyCommand
=> _MyCommand ?? (_MyCommand = new DelegateCommand(async () =>
{
await Task.Run(() => {
///Some Code
});
}));
}
Всякий раз, когда я запускаю код, я получаю следующую ошибку:
Unable to cast object of type 'WindowsApp2.ViewModels.SettingsPartViewModel' to type 'WindowsApp2.ViewModels.MyViewModel'.
Что здесь не так?