首页 > 解决方案 > UserControl的DataContext:直接设置为viewmodel

问题描述

我有一个 wpf 用户控件和一个对应的视图模型(ChamberVm)。

在 viewmodel 中有一个名为“UnitStatus”的属性,但我遇到了绑定错误:

System.Windows.Data Error: 40 : BindingExpression path error: 'UnitStatus' property not found on 'object' ''String' (HashCode=-1814504727)'. BindingExpression:Path=UnitStatus; DataItem='String' (HashCode=-1814504727); target element is 'VacGram' (Name='sysdgm'); target property is 'UnitStatus' (type 'KeyValuePair`2')

我注意到错误可能与控件标题部分中的 DataContext 设置有关:

             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:dgm="clr-namespace:VacSym;assembly=VacSymDgm"             
             xmlns:v="clr-namespace:VacViews"    
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="400"
             DataContext="ChamberVm">
    <Grid Name="gridMain">
        <Grid.RowDefinitions>
            <RowDefinition Height="0*"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="15"></RowDefinition>
        </Grid.RowDefinitions>
        <DockPanel Grid.Row="1">
            <DockPanel x:Name="pnlDgm" Background="Transparent" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                <dgm:VacGram x:Name="sysdgm" UnitStatus="{Binding UnitStatus}" DiagramFile="{Binding DiagramFile}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
            </DockPanel>

       . . .

我想知道:

1、为什么这不正确(?)

    DataContext="ChamberVm"

2、错误信息中的“String”是什么意思:

    ...not found on 'object' ''String'

标签: wpfdata-bindingwpf-controls

解决方案


那作业

DataContext="ChamberVm"

将字符串分配给"ChamberVm"DataContext 属性。

为了分配 ChamberVm 类的实例,您必须编写以下内容,并带有适当的命名空间前缀:

<UserControl ...>
    <UserControl.DataContext>
        <v:ChamberVm/>
    </UserControl.DataContext>
    ...
</UserControl>

通常,您应该完全避免显式分配 DataContext 属性。

您可以将 UserControl 放在 DataTemplate 中,该 DataTemplate 应用于例如 ContentControl,该 ContentControl 具有分配给其 Content 属性的 ChamberVm 对象。然后将自动设置 UserControl 的 DataContext。


推荐阅读