我在Silverlight中有一个带有DependencyProperty的自定义控件。 如果控件本身改变了属性的值,那很好。但是,如果在服务器上更改了值,则控件必须重新加载其内容。
因此,在我的PropertyChangedCallback例程中,我希望能够检查是否是更改了值的控件,或者是否在服务器上更改了(在这种情况下,需要重新加载内容)。
控件是一个文本框,当它改变时,我正在做一个SetValue来改变DependencyProperty值,但是PropertyChangedCallback例程不知道它是控制它的控件,还是服务器。
如何检查调用PropertyChangedCallback的位置?
依赖属性:
Public Shared HtmlHolderProperty As DependencyProperty =
DependencyProperty.Register("HtmlHolder",
GetType(String),
GetType(HTMLEditor),
New PropertyMetadata(Nothing, New PropertyChangedCallback(AddressOf OnHtmlHolderChanged)))
依赖属性更改处理程序:
Private Shared Sub OnHtmlHolderChanged(d As DependencyObject, e As DependencyPropertyChangedEventArgs)
Dim hte As HTMLEditor = DirectCast(d, HTMLEditor)
Dim newhtml As String = If(e.NewValue Is Nothing, "", e.NewValue)
Dim oldhtml As String = If(e.OldValue Is Nothing, "", e.OldValue)
If newhtml <> m_HtmlHolder AndAlso ControlUpdate > ControlUpdateTracker Then
hte.htb.Load(Format.HTML, newhtml)
ControlUpdateTracker = ControlUpdateTracker + 1
End If
m_HtmlHolder = newhtml
End Sub
结合:
Private Sub CreateBindings(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
Dim control As HTMLEditor = DirectCast(sender, HTMLEditor)
Dim context As IContentItem = DirectCast(control.DataContext, IContentItem)
Dim binding As Data.Binding
binding = New Data.Binding("Value") With {
.Source = context,
.Mode = Data.BindingMode.TwoWay
}
Me.SetBinding(HTMLEditor.HtmlHolderProperty, binding)
End Sub
控制_ContentChanged:
Private Sub htb_ContentChanged(sender As Object, e As RichTextBoxEventArgs) Handles htb.ContentChanged
Dim htb As Liquid.RichTextBox = DirectCast(sender, Liquid.RichTextBox)
SetValue(HtmlHolderProperty,htp.HTML)
End Sub
答案 0 :(得分:0)
大概是在设置控件的值时使用setter?
如果是这样,只需在setter中的SetValue调用之前和之后设置一个标志。然后,您可以查看更改是否来自依赖项属性的事件处理程序内的控件本身。
为C#代码道歉,正如你所说的VB.Net,但你明白了。
protected bool LocallySet {get;set;}
public bool MyProperty
{
get { return (bool)GetValue(MyDPProperty); }
set
{
LocallySet = true;
SetValue(MyDPProperty, value);
LocallySet = false;
}
}
如果您遇到大量重叠控制事件的问题,请尝试使用计数器:
protected int _LocallySetCount;
public bool MyProperty
{
get { return (bool)GetValue(MyDPProperty); }
set
{
_LocallySetCount++;
SetValue(MyDPProperty, value);
_LocallySetCount--;
}
}
如果您正在处理一项或多项控制变更,则计数将为非零。
如果你可以发布你的财产的代码,那会很有帮助。