将TextBox绑定到对象WPF

时间:2016-05-20 20:50:44

标签: c# wpf xaml data-binding

我试图让TextBox显示窗口的CurrentDialog属性的stringBody属性。这是XAML部分:

 <TextBox x:Name="ComposerBox" Height="90.302" Margin="311,0,141.355,10" 
...
Text="{Binding Body}"
ScrollViewer.CanContentScroll="True" SpellCheck.IsEnabled="True"       
 VerticalAlignment="Bottom">

这是来自windows构造函数的字符串:

MessagingBox.DataContext = CurrentDialog;

我还尝试将DataContext设置为此而没有结果。 以下是CurrentDialog的定义方式:

private MessageDialog CurrentDialog { get; set; }

这里是MessageDialog类的定义:

   [Serializable][DataContract]
public class MessageDialog
{
    public string Name { get; private set; }
    public UserData User { get; private set; }

    private List<Message> Dialog = new List<Message>();
    public string Body { get; private set; }

    public MessageDialog(UserData data)
    {
        Name = data.Username;
        User = data;
        Body = "";
    }

    public void Add(Message msg)
    {
        Dialog.Add(msg);
        Body += $"{msg.From}: {msg.Body} \n\n";
    }

}

}

绑定根本不起作用。我也希望它是单向的。

1 个答案:

答案 0 :(得分:0)

Text="{Binding CurrentPerson.Body}"

不确定为什么绑定路径包含CurrentPerson,它应该是CurrentDialog,但即使那不应该在那里。由于DataContext已设置为CurrentDialog,因此您只需将文本绑定到:

即可
Text="{Binding Body}"

您需要实现INotifyPropertyChanged,以便WPF知道属性何时更改:

[Serializable][DataContract]
public class MessageDialog : INotifyPropertyChanged
{
    #region public string Body
    private string m_Body;
    public string Body
    {
        get { return m_Body; }
        private set
        {
            if (m_Body == value)
                return;

            m_Body = value;
            this.NotifyPropertyChanged();
        }
    }
    #endregion

    #region INotifyPropertyChanged Members
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName]string propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion
}