内部のテキストが有効な番号でない場合、色が変わるUserControl TextBoxを作成しています。UserControlプロパティのトリガがコードの背後から変更されました
これは、クラスの宣言です:
public partial class ValidatedNumberBox : UserControl, INotifyPropertyChanged
{
public bool IsValid { get; set; }
public static readonly DependencyProperty IsValidProperty = DependencyProperty.RegisterAttached(
nameof(IsValid), typeof(bool), typeof(ValidatedNumberBox), new PropertyMetadata(true));
public ValidatedNumberBox()
{
InitializeComponent();
IsValid = CheckValidity();
}
private void PART_TextBox_OnTextChanged(object sender, TextChangedEventArgs e)
{
IsValid = CheckValidity();
OnPropertyChanged(nameof(IsValid));
TextChanged?.Invoke(sender, e);
}
private bool CheckValidity()
{
return !PART_TextBox.Text.Any(char.IsLetter);
}
#region INotify
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
XAMLは、単にテキストボックスです:
<UserControl x:Class="fisWPF.Controls.ValidatedNumberBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid>
<TextBox Name="PART_TextBox" TextChanged="PART_TextBox_OnTextChanged" />
</Grid>
私はプロパティIsValid
があるときに変更する境界線を取得しようとしています偽のように:
<Style TargetType="{x:Type Controls:ValidatedNumberBox}">
<Setter Property="BorderBrush" Value="Transparent"/>
<Setter Property="BorderThickness" Value="2"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Controls:ValidatedNumberBox}">
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}"
Padding="{TemplateBinding Padding}"
SnapsToDevicePixels="True">
<ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}"
Content="{TemplateBinding Content}"
ContentStringFormat="{TemplateBinding ContentStringFormat}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsValid" Value="False">
<Setter Property="BorderBrush" Value="Red"/>
<Setter Property="BorderThickness" Value="20"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
False
からTrue
にトリガーを変更すると、赤い枠線がコントロールに表示されます。たとえば、IsValid
をCheckBoxのIsChecked
プロパティにバインドすると、それも機能します。ボーダーを変更しない唯一のことは、コードの背後にある値を変更することです。わかるように、私はこのページの多くの質問に対する答えと同じように、INorifyPropertyChangedインターフェースを使ってみました。しかし、PropertyChanged
イベントの値は常にnullで、TextBoxに文字を書くと何も起こりません。