【发布时间】:2015-11-20 09:07:03
【问题描述】:
我目前收到以下错误
System.Windows.Data Error: 40 : BindingExpression path error: 'EthernetView' property not found on 'object' ''LabelTextBox' (Name='Root')'. BindingExpression:Path=EthernetView.SessionName; DataItem='LabelTextBox' (Name='Root'); target element is 'LabelTextBox' (Name='Root'); target property is 'Text' (type 'String')
当我将数据绑定到像
这样的自定义控件时<controls:LabelTextBox Grid.Column="0" Padding="10,5,10,0" LabelText="Name" Text="{Binding EthernetView.SessionName}"
TextWidth="175" IsReadOnly="True" IsError="False" HorizontalAlignment="Right"/>
我很确定我的对象上的 Dependency 属性设置正确
public partial class LabelTextBox : UserControl, INotifyPropertyChanged
{
public string Text
{
get { return LblTextBox.Text; }
set
{
SetValue(TextProperty, value);
LblTextBox.Text = value;
PropertyChanged(this, new PropertyChangedEventArgs("Text"));
}
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register(
"Text",
typeof(string),
typeof(LabelTextBox),
new PropertyMetadata(default(string), OnTextPropertyChanged));
private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
LabelTextBox source = d as LabelTextBox;
source.LblTextBox.Text = e.NewValue as string;
}
}
自定义控件的 xaml 看起来像
<UserControl x:Class="Project.LabelTextBox"
x:Name="Root"
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"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
mc:Ignorable="d"
d:DesignHeight="20" d:DesignWidth="300">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition x:Name="TextWidthColumn" Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="LeftLabel" Grid.Column="0" Foreground="Black" Padding="0,0,10,0" VerticalAlignment="Center" FontSize="12"
Text="{Binding LabelText, ElementName=Root, Mode=TwoWay}"/>
<Border x:Name="TextBoxBorder" Grid.Column="1" BorderThickness="2" Background="#FAFAFAFA">
<TextBox x:Name="LblTextBox" VerticalAlignment="Center" Margin="1" FontSize="12" Text="{Binding Text}"
TextChanged="LblTextBox_TextChanged" KeyDown="OnKeyDownHandler"/>
</Border>
<Image x:Name="ErrorImage" Grid.Column="2" Source="pack://application:,,,/Project;component/Images/RedX.ico" Height="12" Width="12"/>
<TextBlock x:Name="RightLabel" Grid.Column="3" Foreground="Black" Padding="10,0,0,0" VerticalAlignment="Center" FontSize="12"
Text="{Binding LabelText, ElementName=Root, Mode=TwoWay}"/>
</Grid>
</UserControl>
代码在运行时正常工作,但我想清理输出错误。谁能给我一些有关如何解决此错误的见解。
【问题讨论】:
-
这意味着您的LabelTextBox DataContext 不包含EthernetView,因此您必须绑定到相关源并找到拥有它的祖先。如果没有看到视图模型以及它是如何连接起来的,很难回答这个问题。