【发布时间】:2016-03-08 12:06:07
【问题描述】:
我在 UserControl 中为 TextBox Binding 写了一点 string Dependency Property 以将其绑定到另一个,但它不会更新。
用户控制代码隐藏:
public static readonly DependencyProperty MessageTextSendProperty =
DependencyProperty.Register("MessageTextSend", typeof(string), typeof(MessagingControl),
new PropertyMetadata(default(string)));
public string MessageTextSend
{
get { return (string)GetValue(MessageTextSendProperty); }
set { SetValue(MessageTextSendProperty, value); }
}
用户控件 XAML:
<TextBox Text="{Binding Path=MessageTextSend,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type local:MessagingControl}}}" />
我是这样使用它的:
<UserControl x:Class="SomeProject.View.ChatView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:command="http://www.galasoft.ch/mvvmlight"
xmlns:control="clr-namespace:SomeProject.View.Control"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:model="clr-namespace:SomeProject.Model"
DataContext="{Binding Chat,
Source={StaticResource Locator}}"
FontSize="15"
d:DesignHeight="500"
d:DesignWidth="700"
mc:Ignorable="d">
<control:MessagingControl Grid.Column="0"
MessageBubbleCollection="{Binding MessageCollection}"
MessageTextSend="{Binding Message}"
SendCommand="{Binding SendMessageCommand}" />
</UserControl>
public string Message
{
get { return _message; }
set { Set(ref _message, value); }
}
如果我设置 Message 属性,TextBox 不会改变它的 Text,如果 TextBox Text 是通过键盘设置的,它也不会改变 Property。
我会错过什么?
编辑:添加了带有 DataContext 的 UserControl 标记
【问题讨论】:
-
您可能忘记将 MessagingControl(或其父元素之一)的 DataContext 设置为具有 Message 属性的视图模型类的实例。
-
在我看来你只是在一个方向上绑定。如果您希望用户在文本框中输入更新 DP,则需要双向绑定。
BindingMode.TwoWay -
@Okuma.Scott
TextBox.Text属性默认绑定双向。 -
您是否缺少
UpdateSourceTrigger=PropertyChanged,它在Textproperty发生更改时触发。默认情况下,它将仅在LostFocus上更新 -
@Gopichandar 虽然设置
UpdateSourceTrigger=PropertyChanged可能有意义,但这并不能解释为什么当Message 属性发生变化时“TextBox 不会改变它的文本”。
标签: c# wpf xaml user-controls dependency-properties