![](/img/trans.png)
[英]Can I set my user control datacontext in xaml via a dependency property bound to a property on the parent control in wpf?
[英]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.