我完全按照你的要求做了。UserControl
我用一个TextBlock
和创建了一个Button
。如果输入的文本TextBlock
很长,则Button
仍然看不见,这MouseOver
完全符合您的需要。但是,如果输入的文本TextBlock
足够小,则Button
仍然可见。
注意:HorizontalAlignment = Left
必须设置在Button
.
Window3.xaml
<Window x:Class="WpfStackOverflow.Window3"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:uc="clr-namespace:WpfStackOverflow"
Title="Window3" Height="300" Width="300" SizeToContent="WidthAndHeight">
<StackPanel>
<uc:UserControl1 Width="200" Height="35"/>
</StackPanel>
</Window>
UserControl.1.xaml
<UserControl x:Class="WpfStackOverflow.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
xmlns:local="clr-namespace:WpfStackOverflow"
Background="Bisque"
Height="25">
<StackPanel x:Name="DckPnl" Height="25" Orientation="Horizontal">
<TextBlock x:Name="Tb" MouseEnter="Tb_MouseEnter_1" MouseLeave="Tb_MouseLeave_1" FontFamily="Arial" Text="some content , let's say customer name some content, let's say customer name" Background="AliceBlue"/>
<Button x:Name="Btn" Visibility="Hidden" Content="Edit" Width="35" Height="25" Margin="0 0 0 0" HorizontalAlignment="Left"/>
</StackPanel>
</UserControl>
UserControl1.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace WpfStackOverflow
{
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
private void Tb_MouseEnter_1(object sender, MouseEventArgs e)
{
Thickness newMargin = new Thickness();
FormattedText f = new FormattedText(Tb.Text,
new System.Globalization.CultureInfo("en-US"),
System.Windows.FlowDirection.LeftToRight,
new Typeface("Arial"),
Tb.FontSize, Brushes.Black);
if (f.Width > this.ActualWidth)
newMargin = new Thickness((this.ActualWidth - f.Width) - Btn.ActualWidth, 0, 0, 0);
else
newMargin = Btn.Margin;
Btn.Margin = newMargin;
Btn.Visibility = System.Windows.Visibility.Visible;
}
private void Tb_MouseLeave_1(object sender, MouseEventArgs e)
{
Btn.Margin = new Thickness(0, 0, 0, 0);
Btn.Visibility = System.Windows.Visibility.Hidden;
}
}
}