WPF文本框绑定错误

时间:2017-08-16 13:46:09

标签: wpf binding textbox

我无法弄清楚为什么我一直收到此错误,当我在GUI中对tb_Name TextBox进行更改时,Name中的设置永远不会被调用。

  

System.Windows.Data错误:40:BindingExpression路径错误:'名称'   在'object'''String'(HashCode = 2106982518)'上找不到属性。   BindingExpression:路径=名称; DataItem ='String'(HashCode = 2106982518);   target元素是'TextBox'(Name ='tb_Name');目标属性是   'Text'(输入'String')

XAML

<UserControl
             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:ConfigStudioUI.Controls" x:Class="ConfigStudioUI.Controls.DeviceTypeTabCtrl" 
             mc:Ignorable="d"  x:Name="DeviceTypeUC" Loaded="DeviceType_Loaded"
             d:DesignHeight="400" d:DesignWidth="600" Background="#FF00C8FF"  
           >
    <Grid>
    <TabControl Background="#FF00FF99" FontSize="14" 
    TabStripPlacement="Left" Margin="0, 0, 0, 10" >
    <TabItem Name="PropertiesTab" Header="Properties">
    <Grid>
    <Grid  >
    <TextBox Text="{Binding Source=DeviceType, Path=Name, Mode=TwoWay}" 
    TabIndex="0" x:Name="tb_Name" HorizontalAlignment="Stretch" Height="32" 
        Margin="159,28,5.2,0"  VerticalAlignment="Top"  />
    </Grid>
                </Grid>
            </TabItem>
     </TabControl>
</UserControl>

背后的代码

public partial class DeviceTypeTabCtrl : UserControl
{
public DeviceType DeviceType { get; set; }

public DeviceTypeTabCtrl(DeviceType deviceTypeObject, DeviceTypeGroup 
deviceTypeGroupObject)
    {
        InitializeComponent();
        DataContext = this;
        this.DeviceType = new DeviceType();
        this.DeviceType = deviceTypeObject;
        this.tb_Name.Text = deviceTypeObject.Name;
        this.DeviceType.DeviceTypeGroupGUID = 
        deviceTypeGroupObject.DeviceTypeGroupGUID;
    }
}

public class DeviceType : INotifyPropertyChanged
{
    /// <summary>
    /// Name
    /// </summary>
    public string Name
    {
        get
        {
            return this.name;
        }
        set
        {
            if (this.name != value)
            {
                this.name = value;
                NotifyPropertyChanged("Name");
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我最终在这里找到答案:How To Bind a Property to Textbox using MVVM and MVVM toolkit?

我还更新了对象名称(DeviceTypeObj)以使其更清晰。

<TextBox Text="{Binding DeviceTypeObj.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" TabIndex="0" 
                                 x:Name="tb_Name" HorizontalAlignment="Stretch" Height="32" Margin="159,28,5.2,0"  VerticalAlignment="Top"  />