隐藏/显示XAML元素或阻止LostFocus事件

2sbarzqh  于 2022-12-16  发布在  其他
关注(0)|答案(2)|浏览(131)

我有一个包含两个StackPanel的页面,每个包含一个TextBox和一个Button:

<StackPanel x:Name="Row1">
<TextBox x:Name="TextBox1" Text="" GotFocus="OnFocusHandler" LostFocus="OffFocusHandler"/>
<Button x:Name="Button1" Content="Convert" Click="OnClickHandler" Visibility="Collapsed"/>
</StackPanel>

<StackPanel x:Name="Row2">
<TextBox x:Name="TextBox2" Text="" GotFocus="OnFocusHandler" LostFocus="OffFocusHandler"/>
<Button x:Name="Button2" Content="Convert" Click="OnClickHandler" Visibility="Collapsed"/>
</StackPanel>

我想做以下几点:

  • 当一个文本框具有焦点时,必须隐藏另一个文本框,并显示相应的按钮
  • 当一个文本框失去焦点时,我们会回到原来的显示:只有空文本框是可见的
  • 我不希望该按钮能够触发OffFocusHandler

这是我为这三个处理程序编写的当前代码:

private void OnFocusHandler(object sender, RoutedEventArgs e)
{
    TextBox SenderTextBox = (TextBox)sender;

    if (SenderPanel.Name == "TextBox1")
    {
        Button1.Visibility = Visibility.Visible;
    }
    else if (SenderPanel.Name == "TextBox2")
    {
        Button2.Visibility = Visibility.Visible;
    }
}

private void OffFocusHandler(object sender, RoutedEventArgs e)
{
    TextBox1.Text = "";
    TextBox2.Text = "";
    Button1.Visibility = Visibility.Collapsed;
    Button2.Visibility = Visibility.Collapsed;
}

private void OnClickHandler(object sender, RoutedEventArgs e)
{
    // some stuff unrelated to my issue
}

我怎样才能避免点击按钮触发OffFocusHandler代码?有没有其他的方法来编写这个代码?我是一个完全的初学者,所以我可能想不出正确的方法。

m3eecexj

m3eecexj1#

您只需绑定到Xaml中的TextBox.IsFocused属性,然后使用BooleanToVisibilityConverter来显示/隐藏按钮。
示例:

<Window x:Class="WpfApplication4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication4"
       Title="MainWindow" Height="300" Width="400" Name="UI" >
    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="BoolTovisible" />
    </Window.Resources>

    <Grid>
        <StackPanel x:Name="Row1" Height="54" VerticalAlignment="Top">
            <TextBox x:Name="TextBox1" Text="" />
            <Button x:Name="Button1" Content="Convert" Visibility="{Binding ElementName=TextBox1, Path=IsFocused, Converter={StaticResource BoolTovisible}}"/>
        </StackPanel>

        <StackPanel x:Name="Row2" Margin="0,60,0,0" Height="51" VerticalAlignment="Top">
            <TextBox x:Name="TextBox2" Text="" />
            <Button x:Name="Button2" Content="Convert" Visibility="{Binding ElementName=TextBox2, Path=IsFocused, Converter={StaticResource BoolTovisible}}"/>
        </StackPanel>
    </Grid>
</Window>
ttvkxqim

ttvkxqim2#

每个元素都有一个Visibility标记,默认情况下为“Visible”,但您可以指定“Hidden”或“Collapsed”,如下所示:

<RadioButton Margin="20,118,318,-43" GroupName="MCSites"  Visibility="Hidden">
        Radio Button Description
</RadioButton>

相关问题