【发布时间】:2026-02-06 00:05:01
【问题描述】:
我正在使用模板 10 和 MVVM 创建 UWP 应用。我的要求是创建具有自己的依赖属性以及 ViewModel 的 UserControl。
我的要求:
- 在单击按钮时调用父 ViewModel 命令。
- 从 UserControl ViewModel 绑定 TexBlock 文本
我的用户控件如下所示:
<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); }
}
}
UserControl 视图模型:
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'.
这里出了什么问题?
【问题讨论】:
标签: mvvm data-binding user-controls uwp template10