我在UserControl中为TextBox绑定编写了一个小string
依赖项属性,将其绑定到另一个,但它不会更新。
UserControl CodeBehind:
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); }
}
UserControl 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 Property,TextBox将不会更改其Text,如果TextBox Text是通过键盘设置的,它也不会更改Property。
我能错过什么?
编辑:使用DataContext添加了UserControl标记
答案 0 :(得分:0)
以下是完整的工作示例代码。
<强> MessagingControl.xaml 强>
<StackPanel>
<TextBox Text="{Binding Path=MessageTextSend, UpdateSourceTrigger=PropertyChanged,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type local:MessagingControl}}}" />
</StackPanel>
<强> MessagingControl.xaml.cs 强>
public MessagingControl()
{
InitializeComponent();
}
public static readonly DependencyProperty MessageTextSendProperty =
DependencyProperty.Register("MessageTextSend", typeof(string), typeof(MessagingControl),
new FrameworkPropertyMetadata(default(string), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public string MessageTextSend
{
get { return (string)GetValue(MessageTextSendProperty); }
set { SetValue(MessageTextSendProperty, value); }
}
<强> MainWindow.xaml 强>
<StackPanel>
<local:MessagingControl MessageTextSend="{Binding Message}" x:Name="uc"/>
<TextBlock Text="{Binding ElementName=uc, Path=MessageTextSend}" />
</StackPanel>
<强> MainWindow.xaml.cs 强>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new SampleClass() { Message = "My Message" };
}
}
public class SampleClass
{
public string Message { get; set; }
}