gpt4 book ai didi

wpf - 在 WPF 中,如何在具有焦点的窗口部分周围放置边框?

转载 作者:行者123 更新时间:2023-12-05 00:41:16 25 4
gpt4 key购买 nike

我有一个有两个主要区域的窗口。一个是 ScrollViewer 内的 TextBox,另一个是 TabControl。我想在当前具有焦点的部分周围有一个红色边框,所以我编写了以下代码来做到这一点

xml

<ScrollViewer BorderBrush="Red" 
BorderThickness="0"
GotFocus="Border_GotFocus"
LostFocus="Border_LostFocus">
<TextBox/>
</ScrollViewer>
<TabControl BorderBrush="Red"
BorderThickness="0"
GotFocus="Border_GotFocus"
LostFocus="Border_LostFocus">
</TabControl>

代码
private void Border_LostFocus(object sender, RoutedEventArgs e)
{
var control = sender as Control;
if (control != null)
{
control.BorderThickness = new Thickness(0);
}
}

private void Border_GotFocus(object sender, RoutedEventArgs e)
{
var control = sender as Control;
if (control != null)
{
control.BorderThickness = new Thickness(2);
}
}

问题是,如果我单击 TextBox,它不会更新 ScrollViewer 周围的边框。如果我点击 TabControl 中的一个选项卡,它会更新边框,以便我可以看到边框,但当我点击其他地方时不会“删除”它。有没有更好的方法来做到这一点?

最佳答案

首先,我强烈建议不要使用代码并将其全部保存在 XAML 中。

其次,我还建议使用 Border去做这个。

第三,我会在您的样式触发器中使用 IsKeyboardFocusedWithin。

<Window.Resources>
<Style x:Key="FocusedBorder" TargetType="Border">
<Setter Property="BorderThickness" Value="2"></Setter>
<Setter Property="BorderBrush" Value="Transparent"></Setter>
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="BorderBrush" Value="Red"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel Width="400">
<ScrollViewer>
<Border Style="{StaticResource FocusedBorder}">
<TextBox>
</TextBox>
</Border>
</ScrollViewer>
<TabControl>
<TabItem Header="Foo">
<Border Style="{StaticResource FocusedBorder}">
<TextBox></TextBox>
</Border>
</TabItem>
<TabItem Header="Bar">
<Border Style="{StaticResource FocusedBorder}">
<TextBox></TextBox>
</Border>
</TabItem>
</TabControl>
</StackPanel>

关于wpf - 在 WPF 中,如何在具有焦点的窗口部分周围放置边框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3106894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com