C# 在自定义控件上进行单向到源/双向绑定
我有一个带有dependency属性的自定义控件,定义如下:C# 在自定义控件上进行单向到源/双向绑定,c#,wpf,data-binding,custom-controls,C#,Wpf,Data Binding,Custom Controls,我有一个带有dependency属性的自定义控件,定义如下: public class TemplatedTextBox : TextBox { public static readonly DependencyProperty SearchStringProperty = DependencyProperty.Register("SearchString", typeof(string), typeof(TemplatedTextBox), new UIProperty
public class TemplatedTextBox : TextBox
{
public static readonly DependencyProperty SearchStringProperty =
DependencyProperty.Register("SearchString", typeof(string), typeof(TemplatedTextBox), new UIPropertyMetadata(string.Empty));
public string SearchString
{
get { return (string)GetValue(SearchStringProperty); }
set { SetValue(SearchStringProperty, value); }
}
}
我使用以下控件模板:
<WpfApp:TemplatedTextBox>
<WpfApp:TemplatedTextBox.Template>
<ControlTemplate TargetType="{x:Type WpfApp:TemplatedTextBox}">
<StackPanel Height="20" Orientation="Horizontal">
<TextBlock Text="Search String :"/>
<TextBox x:Name="SearchTextBox" Width="200" Text="NEED TO BE BINDED TO SearchString!"/>
</StackPanel>
</ControlTemplate>
</WpfApp:TemplatedTextBox.Template>
</WpfApp:TemplatedTextBox>
这也没什么用
Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SearchString, Mode=TwoWay}"
及
当我以编程方式更改SearchString
时,TextBox
上的Text
可以在一个方向上正常工作,但不能在另一个方向上进行更改
我还尝试将SearchString
作为常规属性,并在各种模式下使用RelativeSource
对其进行绑定,但没有成功
在常规视图到视图模型的绑定中,这是一件非常简单的事情,那么我在这里缺少了什么呢?我刚刚尝试了它,它按照预期工作。
是否可能是简单的原因,例如,您在输入字符后没有离开文本框,因此绑定不会触发
尝试添加UpdateSourceTrigger=PropertyChanged
,以触发对输入的每个字符的绑定。我不敢相信我在UpdateSourceTrigger=PropertyChanged
这样愚蠢的事情上一直失败。。。谢谢你@Omribitan每个人都这么做。textbox没有将propertychanged作为默认值,这总是让我很恼火,因为它对于验证是有意义的。
Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SearchString, Mode=TwoWay}"
Text="{TemplateBinding SearchString}"