原文: 【C#/WPF】TextBlock/TextBox/Label编辑文字的问题
标题有点描述不清,就当是为了方便自己用时易于搜索到。
总之需求是:显示用户信息(文字)时,允许用户编辑自己的信息。
效果图如下:
点击【编辑】按钮前:
点击【编辑】按钮后,允许编辑:- 别吐槽为甚性别还能再改。。。我就是意思意思这个效果
- 使用了样式,但不是本文关注点,于是省略
- 按钮的作用也不是本文关注点,省略
一种解决思路:
正常显示用的TextBlock,然后在它上面放一个TextBox并隐藏。点击【编辑】按钮后再显示TextBox,达到看起来像是编辑文字的效果!
前台代码:
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="60"/>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="60"/>
<ColumnDefinition Width="200"/>
</Grid.ColumnDefinitions>
<!-- 用户名 -->
<TextBlock Grid.Row="0" Grid.Column="0" Text="用户名:" FontSize="16" VerticalAlignment="Center" HorizontalAlignment="Left"/>
<Grid Grid.Row="0" Grid.Column="1" Margin="5" Grid.ColumnSpan="2" Height="30" VerticalAlignment="Center" HorizontalAlignment="Left">
<Label x:Name="userId" FontSize="16" Width="180"/>
<TextBox x:Name="editUserId" FontSize="16" Width="180" Visibility="Collapsed"/>
</Grid>
<!-- 编辑 -->
<Grid Grid.Row="0" Grid.Column="3" Margin="10,0,10,0" VerticalAlignment="Center" HorizontalAlignment="Right">
<Button x:Name="editBtn" Command="{Binding EditCommand}" Style="{StaticResource myButton1}" Content="编辑" Width="60" Height="25"/>
<Button x:Name="editConfirmBtn" Command="{Binding EditConfirmCommand}" Style="{StaticResource myButton1}" Content="确定" Width="60" Height="25" Margin="0,0,0,1" Visibility="Collapsed"/>
<Button x:Name="editCancelBtn" Command="{Binding EditCancelCommand}" Style="{StaticResource myButton1}" Content="取消" Width="60" Height="25" Margin="-70,0,70,0" Visibility="Collapsed"/>
</Grid>
<!-- 昵称 -->
<TextBlock Grid.Row="1" Grid.Column="0" Text="昵称:" FontSize="16" VerticalAlignment="Center" HorizontalAlignment="Left"/>
<Grid Grid.Row="1" Grid.Column="1" Margin="5" Grid.ColumnSpan="2" Height="30" VerticalAlignment="Center" HorizontalAlignment="Left">
<Label x:Name="nickName" FontSize="16" Width="180"/>
<TextBox x:Name="editNickName" FontSize="16" Width="180" Visibility="Collapsed"/>
</Grid>
<!-- 性别 -->
<TextBlock Grid.Row="1" Grid.Column="2" Text="性别:" FontSize="16" VerticalAlignment="Center" HorizontalAlignment="Left"/>
<Grid Grid.Row="1" Grid.Column="3" Margin="5" Height="30" VerticalAlignment="Center" HorizontalAlignment="Left">
<Label x:Name="sex" FontSize="16" Width="180"/>
<StackPanel Orientation="Horizontal">
<RadioButton x:Name="editSexMale" GroupName="sex" Content="男" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="0" Visibility="Collapsed"/>
<RadioButton x:Name="editSexFemale" GroupName="sex" Content="女" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="30,0,0,0" Visibility="Collapsed"/>
</StackPanel>
</Grid>
</Grid>
这里【编辑】、【确认】、【取消】三个按钮的Command绑定到点击事件,就是控制这三个按钮组的显隐和TextBox的显隐切换,实现界面效果后再添加数据的修改和上传逻辑。