Hi,@Alexander Landa. Welcome to Microsoft Q&A. It is possible to create your own attached properties in WPF, similar to Validation.Errors, for various purposes such as custom validation, behavior addition, or data binding facilitation.
Here's an example of create a custom attached property MyValidation.XYZ:
<StackPanel>
<TextBox Width="100" Height="60" Text="{Binding MyValue}" local:MyValidation.XYZ="{Binding MyValue}" />
</StackPanel>
Codebehind:
public partial class MainWindow : Window,INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
private string myValue;
public string MyValue
{
get { return myValue; }
set { myValue = value; OnPropertyChanged(); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
public static class MyValidation
{
public static readonly DependencyProperty XYZProperty =
DependencyProperty.RegisterAttached("XYZ", typeof(string), typeof(MyValidation),
new PropertyMetadata(null, OnXYZPropertyChanged));
public static string GetXYZ(DependencyObject obj)
{
return (string)obj.GetValue(XYZProperty);
}
public static void SetXYZ(DependencyObject obj, string value)
{
obj.SetValue(XYZProperty, value);
}
private static void OnXYZPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// This method will be called whenever the value of XYZ property changes
// You can perform any necessary actions here
string newValue = (string)e.NewValue;
string oldValue = (string)e.OldValue;
// Example: Logging the change
System.Diagnostics.Debug.WriteLine($"XYZ property changed from '{oldValue}' to '{newValue}'");
}
}
The result:
When MyValue changes, a meesage is displayed in the output window.
XYZ property changed from '' to 'FFF' XYZ property changed from 'FFF' to 'DDD'
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.