有趣的是,这绝对是一种罕见的情况,我很想听到更多关于它的功能。
您是否考虑通过绑定或 GetValue 为读取提供无效值(例如 null),而只是没有 CLR getter 的想法?
要么使用私有 DependencyProperty 来存储您关心的“真实”值,要么只使用私有成员变量。
在属性更改回调中,始终将值恢复为原始值,同时存储设置的新值。
我现在大部分时间都在做 Silverlight 控件开发,所以这个属性在 WPF 和 Silverlight-land 中工作,并且不使用强制或类似的任何有趣的东西。不过,也许它会让你走上正确的轨道。
/// <summary>
/// Sets the write-only dependency property.
/// </summary>
public string MyWriteOnlyDependencyProperty
{
set { SetValue(MyWriteOnlyDependencyPropertyProperty, value); }
}
private string _theRealSetValue;
private bool _ignorePropertyChange;
/// <summary>
/// Identifies the MyWriteOnlyDependencyProperty dependency property.
/// </summary>
public static readonly DependencyProperty MyWriteOnlyDependencyPropertyProperty =
DependencyProperty.Register(
"MyWriteOnlyDependencyProperty",
typeof(string),
typeof(TemplatedControl1),
new PropertyMetadata(null, OnMyWriteOnlyDependencyPropertyPropertyChanged));
/// <summary>
/// MyWriteOnlyDependencyPropertyProperty property changed handler.
/// </summary>
/// <param name="d">TemplatedControl1 that changed its MyWriteOnlyDependencyProperty.</param>
/// <param name="e">Event arguments.</param>
private static void OnMyWriteOnlyDependencyPropertyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TemplatedControl1 source = d as TemplatedControl1;
if (source._ignorePropertyChange)
{
source._ignorePropertyChange = false;
return;
}
string value = e.NewValue as string;
source._theRealSetValue = value;
// Revert, since this should never be accessible through a read
source._ignorePropertyChange = true;
source.SetValue(e.Property, e.OldValue);
}