【发布时间】:2017-05-12 08:31:24
【问题描述】:
public class CustomSearchControl : Control
{
static CustomSearchControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomSearchControl),
new FrameworkPropertyMetadata(typeof(CustomSearchControl)));
CommandManager.RegisterClassCommandBinding(typeof(CustomSearchControl),
new CommandBinding(CustomSearchControl.DeleteCommand, C_DeleteCommand));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
}
static void C_DeleteCommand(object sender, ExecutedRoutedEventArgs e)
{
CustomSearchControl mycontrol = sender as CustomSearchControl;
mycontrol.SearchText = "";
}
public static readonly ICommand DeleteCommand = new RoutedUICommand("DeleteCommand", "DeleteCommand",
typeof(CustomSearchControl),
new InputGestureCollection(new InputGesture[]
{ new KeyGesture(Key.Enter), new MouseGesture(MouseAction.LeftClick) }));
public static readonly DependencyProperty SearchTextProperty =
DependencyProperty.Register("SearchText",
typeof(string),
typeof(CustomSearchControl),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
SearchTextPropertyChanged));
public string SearchText
{
get { return (string)base.GetValue(SearchTextProperty); }
set { base.SetValue(SearchTextProperty, value); }
}
private static void SearchTextPropertyChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
{
CustomSearchControl mycontrol = d as CustomSearchControl;
mycontrol.SearchText = e.NewValue.ToString();
}
}
<ResourceDictionary x:Class="CustomSearchControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplicationCustomSearchControl">
<Style TargetType="{x:Type local:CustomSearchControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomSearchControl}">
<Grid>
<StackPanel Orientation="Horizontal">
<TextBox x:Name="tbSearchTextBox"
Width="200" Height="25"
Text="{TemplateBinding SearchText}">
</TextBox>
<Button x:Name="btnDelete"
Width="50" Height="25"
Content="Delete"
Command="{x:Static local:CustomSearchControl.DeleteCommand}">
</Button>
</StackPanel>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
<Window...>
<Grid>
<local:CustomSearchControl SearchText="{Binding Path=SearchText, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
</Grid>
</Window>
我想创建一个自定义控件,其中包含一个文本框和一个清除文本框的按钮。 如果 TextBox 中的 Text 发生更改,则不会引发 PropertyCallBack。当引发 DeleteCommand 时,也会出现同样的问题。
怎么了?
【问题讨论】:
-
“如果 TextBox 中的文本发生更改,则不会引发 PropertyCallBack” - 不清楚,您能更好地描述问题吗?你的意思是
Text="{TemplateBinding SearchText, UpdateSourceTrigger=PropertyChanged}"(见this)? -
在 MainWindow 中,CustomControl 的 SearchTextProperty 绑定到 ViewModel 中的公共属性“SearchText”,该属性具有 INotifyPropertyChanged。我的意思是 CustomControl 中的 SearchTextPropertyChanged 方法
-
为什么需要回调?
TemplateBinding已经更新TextBox(请参阅@Quarzy 答案)。我理解您的问题,就好像您键入文本并且未调用回调(在绑定将更新源之前不会调用它,因此我对如何输入的评论将在每次更改Text后更新)。