我正在使用
textblock
,其属性绑定到绑定类,我希望焦点 textblock
在某些时间处于活动状态,有什么方法可以绑定 textblock
的焦点状态吗?
<TextBox x:Name="block1" Text="{Binding Text_ , Mode=TwoWay}" Style="{ThemeResource TextFieldStyle}" AllowFocusOnInteraction="True" FontSize="14" MinWidth="274" Height="30" RelativePanel.Below="seperator1" Margin="12 12 12 0" />
建议您为 Textbox 创建依赖属性来更改其焦点状态。
<Grid>
<StackPanel>
<TextBox x:Name="testTextBox" TextWrapping="Wrap" Text="Test Test" Height="113" Width="265"/>
<Button Content="Button" Click="Button_Click"/>
<Button Content="Button" Click="Button_Click_1"/>
</StackPanel>
</Grid>
public sealed partial class MainPage : Page
{
public bool IsFocused = true;
public MainPage()
{
this.InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
IsFocused=true;
testTextBox.SetValue(FocusExtension.IsFocusedProperty, true);
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
IsFocused = false;
testTextBox.SetValue(FocusExtension.IsFocusedProperty, false);
}
}
public static class FocusExtension
{
public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached(
"IsFocused", typeof(bool), typeof(FocusExtension), new PropertyMetadata(false, OnIsFocusedPropertyChanged));
public static bool GetIsFocused(DependencyObject obj)
{
return (bool)obj.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject obj, bool value)
{
obj.SetValue(IsFocusedProperty, value);
}
private static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = (Control)d;
if ((bool)e.NewValue)
{
control.Focus(FocusState.Programmatic);
}
}
}