我正在封装一个我编写的快速且肮脏的水印文本框,以便我可以在我的应用程序中重用它:BetterTextBox。除了使用新文本值更新底层 DataContext 之外,一切都在其中进行。我想我在这里错过了一些简单的东西......
BetterTextBox.xaml:
<UserControl
x:Class="Murray.Base.Controls.BetterTextBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<TextBox Text="{Binding Text, RelativeSource={RelativeSource AncestorType=UserControl}, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock
Margin="3,0,0,1"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Foreground="DarkGray"
IsHitTestVisible="False"
Text="{Binding Watermark, RelativeSource={RelativeSource AncestorType=UserControl}}">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="{x:Null}">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Grid>
</UserControl>
BetterTextBox.xaml.cs:
using System.Windows;
using System.Windows.Controls;
namespace Murray.Base.Controls
{
/// <summary>
/// Interaction logic for BetterTextBox.xaml
/// </summary>
public partial class BetterTextBox : UserControl
{
public BetterTextBox() { InitializeComponent(); }
public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } }
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(nameof(Text), typeof(string), typeof(BetterTextBox));
public string Watermark { get { return (string)GetValue(WatermarkProperty); } set { SetValue(WatermarkProperty, value); } }
public static readonly DependencyProperty WatermarkProperty = DependencyProperty.Register(nameof(Watermark), typeof(string), typeof(BetterTextBox));
}
}
在另一个用户控件中使用 BetterTextBox:
<baseControls:BetterTextBox
Width="300"
Margin="5,0,0,0"
Text="{Binding OverrideDistributionEmail}"
Watermark="Enter any override distribution email address(s) here..." />
数据上下文对象上的目标属性:
public string OverrideDistributionEmail { get; set; } = "[email protected]";
我可以在 setter 上放置一个断点,但它永远不会被击中。
试试这个:
RelativeSource Mode=FindAncestor
<TextBox Text="{Binding Text, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, UpdateSourceTrigger=PropertyChanged}" />
代替
<TextBox Text="{Binding Text, RelativeSource={RelativeSource AncestorType=UserControl}, UpdateSourceTrigger=PropertyChanged}" />