在自定义控件上创建单向到源/双向绑定
本文关键字:绑定 创建 自定义控件 | 更新日期: 2023-09-27 18:36:16
我有一个带有依赖项属性的自定义控件,定义如下:
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>
我想以OneWayToSource
或TwoWay
绑定模式将SearchTextBox
的Text
属性绑定到我的SearchString
属性。
我试过:
Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SearchString, Mode=OneWayToSource}"
这不会什么都不做。
Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SearchString, Mode=TwoWay}"
和
Text="{TemplateBinding SearchString}"
当我以编程方式更改SearchString
TextBox
更改的Text
时,这在一个方向上工作正常,但反过来则不行
我还尝试将SearchString
设置为常规属性并在各种Mode
中使用RelativeSource
绑定它,但它不起作用。
在常规的视图到视图模型绑定中,这是一件非常简单的事情,那么我在这里缺少什么?
我刚刚尝试过,它按预期工作。是否可以简单地说,例如,输入字符后您不会离开文本框,因此绑定不会触发?
尝试添加 UpdateSourceTrigger=PropertyChanged
,以触发对输入的每个字符的绑定。