关注autocompletebox中的文本框
本文关键字:文本 autocompletebox 关注 | 更新日期: 2023-09-27 17:49:46
这是我的xaml:
<toolkit:AutoCompleteBox Name="signalNameEditor"
ItemsSource="{Binding MySource}"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
IsTextCompletionEnabled="True"
FilterMode="StartsWith"
ValueMemberPath="Label"
MinimumPrefixLength="3"
MinimumPopulateDelay="800"
Style="{StaticResource autoCompleteBoxStyle}">
<toolkit:AutoCompleteBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Name="textBlock" Text="{Binding Label}"/>
</StackPanel>
</DataTemplate>
</toolkit:AutoCompleteBox.ItemTemplate>
</toolkit:AutoCompleteBox>
所以,我怎么能得到textblock元素在我的视图?我试过了:
var textBlock = signalNameEditor.FindName("textBlock");
,但它是错误的。所以你能帮我解决这个问题或者给我一个正确的解决方案吗?提前谢谢。
谢谢你的回答,这是有效的
var textBlock = ((StackPanel)signalNameEditor.ItemTemplate.LoadContent()).FindName("textBlock") as TextBlock;
但不幸的是,我没有得到我所期望的结果。问题是如何在autocompletebox中获得textbox的焦点,这样当焦点在autocompletebox上时,我可以在那里写一些东西而不用双击。我想我可以在视图里面做点什么
public void SetFocus
{
var textBlock = ((StackPanel)signalNameEditor
.ItemTemplate
.LoadContent())
.FindName("textBlock") as TextBlock;
textBlock.Focus();
}
我知道有很多像这样设置焦点的例子WPF中的自动完成框焦点但我不能让它为我工作。有没有一个解决方案,我可以不写AutoCompleteFocusableBox类?
解决方案更简单。实际上,我需要设置焦点在一个自动完成框的文本框。为此,我使用定义为常规样式的样式http://msdn.microsoft.com/ru-ru/library/dd728668(v=vs.95).aspx
在我看来,在它之后,我可以使用以下命令:
public void SetFocus()
{
var textbox = this.editor.Template.FindName("Text", editor) as TextBox;
textbox.Focus();
}
您可以为文本框编写扩展并设置自定义属性以使其可对焦
例如,你可以这样写扩展类
public static class FocusBehavior
{
#region Constants
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached("IsFocused", typeof (bool?),
typeof (FocusBehavior), new FrameworkPropertyMetadata(IsFocusedChanged));
#endregion
#region Public Methods
public static bool GetIsFocused(DependencyObject obj)
{
return (bool) obj.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject obj, bool value)
{
obj.SetValue(IsFocusedProperty, value);
}
#endregion
#region Event Handlers
private static void IsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var uie = (UIElement) d;
if ((bool) e.NewValue)
uie.Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() => Keyboard.Focus(uie)));
}
#endregion Event Handlers
}
然后在xaml中如下所示:
<UserControl xmlns:behaviours="clr-namespace:Example.Views.Behaviours">
<TextBox TextWrapping="Wrap" Text="TextBox" behaviours:FocusBehavior.IsFocused={Binding IsFocused}/>
我希望这能回答你的问题