繁体   English   中英

用户控件不会在xaml中创建datacontext实例

[英]User control wont create instance of datacontext in xaml

我试图弄清楚为什么我创建的UserControl无法在xaml中设置其DataContext像

<UserControl.DataContext>
    <vm:MainViewModel/>
</UserControl.DataContext>

如果我这样做,它会抛出xamlparse异常,表示DataContext = null。

如果我改为在后面的代码中做

this.DataContext = new MainViewModel();

根本没有问题。

MainView和MainViewModel都是dll项目。 主窗口仅包含MainView。 MainView和MainviewModel代码:

<UserControl x:Class="UmlEditor.view.MainView"
             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" 
             xmlns:local="clr-namespace:UmlEditor.view"
             xmlns:vm="clr-namespace:UmlEditor.ViewModel;assembly=UmlEditor.ViewModel"

             >
<!--This dosent work-->
    <UserControl.DataContext>
        <vm:MainViewModel/>
    </UserControl.DataContext>

    <Grid>
            <Button Command="{Binding HeyCommand}" Content="i work" Width="100" Height="50"/>
    </Grid>
</UserControl>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GalaSoft.MvvmLight.CommandWpf;
using System.Windows.Input;

namespace UmlEditor.ViewModel
{
    public class MainViewModel
    {
        public ICommand HeyCommand { get; private set; }
        public MainViewModel()
        {
            HeyCommand = new RelayCommand(hej);
        }

        private void hej()
        {
            Console.WriteLine("i am the bomb");
        }
    }
}

我终于弄明白了。

因为view和viewmodel都是两个单独的.dll,而app(window)是一个单独的项目。

即使仅直接使用视图,该应用也需要同时引用这两个.dll

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM