wpf - 无法将 View 绑定(bind)到 ViewModel

标签 wpf binding mvvm view viewmodel

我正在尝试做一件最简单的事情:将 View 绑定(bind)到 ViewModel,但由于某种原因它不起作用。

我有主窗口:

<Window x:Class="ImagesToAmazon.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    xmlns:v="clr-namespace:ImagesToAmazon.View"
    xmlns:vm="clr-namespace:ImagesToAmazon.ViewModel" >

<Window.Resources>
    <DataTemplate DataType="{x:Type vm:MainViewModel}">
        <v:MainControl />
    </DataTemplate>
</Window.Resources>

<Grid>

</Grid>

主视图模型:
namespace ImagesToAmazon.ViewModel{
public class MainViewModel {
}}

主控:
<UserControl x:Class="ImagesToAmazon.View.MainControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<StackPanel>
    <Button Content="Button" Height="23" Name="button1" Width="75" />
</StackPanel>

另外,我覆盖 App.OnStartup 来设置 MainWindow 上下文:
public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        var window = new MainWindow();
        var viewModel = new ViewModel.MainViewModel();
        window.DataContext = viewModel;

        window.Show();
    }
}

所有编译,但我没有从 MainControl 中看到我的按钮。
有什么线索吗?

最佳答案

在主窗口中,将 Grid 替换为

<ContentControl Content="{Binding }" />

这将尝试使用当前的 DataContext 作为控件的内容,它会使用你之前定义的 DataTemplate。

关于wpf - 无法将 View 绑定(bind)到 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9499418/

相关文章:

c# - 如何在没有代码隐藏的情况下处理我的 ViewModel 中的 WPF 路由命令?

c# - 删除触发器的正确​​方法

wpf - invokecommandaction使用可以执行吗?

c# - 如何在属性更新后调用方法

C# - 具有动态数量可绑定(bind)属性的类

javascript - addEventListener:如何访问事件

c# - 绑定(bind)到静态属性的一种方法失败

c# - WPF MultiBinding VS 设计器异常

c# - 将 C# 数组传递给 C++ 方法

WPF ListView 列标题对齐