简体   繁体   中英

User control wont create instance of datacontext in xaml

I have tried to figure out why a UserControl i have created cant have its DataContext set in xaml like

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

If i do it throws an xamlparse exception saying DataContext=null.

if i instead in the codebehind do

this.DataContext = new MainViewModel();

there is no problem at all.

the MainView and MainViewModel are both dll projects. The Main Window only contains MainView. MainView and MainviewModel Code:

<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");
        }
    }
}

I Finally figured it out.

as both view and viewmodel are two seperate .dll and the app(window) a seperate project.

The app need reference to both .dll even though it only directly uses view

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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