我正在使用附加行为来记录ScrollBar上的用户操作。
我的代码:
class ScrollBarLogBehavior : Behavior<ScrollBar>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Loaded += new RoutedEventHandler(AssociatedObject_Loaded);
}
void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
{
...
var track = (Track)AssociatedObject.Template.FindName("PART_Track", AssociatedObject);
// ** HERE is the problem: track is null ! **
...
}
如何检测到模板已加载,我可以找到Track?
(当我调用AssociatedObject.Template.LoadContent()
时,结果包含所请求的Track,所以这是时间问题,而不是错误的模板或命名问题)
答案 0 :(得分:1)
我没有找到任何好方法来检测何时加载模板。但是,我确实找到了找到轨道的方法:
- 注册到ScrollBar的Scroll事件(当然,这只能在加载整个模板后发生):
protected override void OnAttached() { base.OnAttached(); _scrollHandler = new ScrollEventHandler(AssociatedObject_Scroll); AssociatedObject.AddHandler(ScrollBar.ScrollEvent,_scrollHandler,true); }
处理Scroll事件时,请删除注册并找到Thumb:
void AssociatedObject_Scroll(对象发送者,ScrollEventArgs e) { var track =(Track)AssociatedObject.Template.FindName(&#34; PART_Track&#34;,Associated if(track == null) 返回; AssociatedObject.RemoveHandler(ScrollBar.ScrollEvent,_scrollHandler); //使用Track完成我的工作 ... }
答案 1 :(得分:0)
如果我理解正确,您希望创建一个附加行为,在加载 ScrollBar
后引用模板部分。
以下应该有效:
internal static class ScrollBarLogBehavior
{
public static readonly DependencyProperty LogUserActionProperty = DependencyProperty.RegisterAttached(
"LogUserAction",
typeof(bool),
typeof(ScrollBarLogBehavior),
new UIPropertyMetadata(default(bool), LogUserActionChanged));
public static bool GetLogUserAction(DependencyObject obj)
{
return (bool)obj.GetValue(LogUserActionProperty);
}
public static void SetLogUserAction(DependencyObject obj, bool value)
{
obj.SetValue(LogUserActionProperty, value);
}
public static void LogUserActionChanged(DependencyObject s, DependencyPropertyChangedEventArgs e)
{
if (s is ScrollBar scrollBar)
{
scrollBar.Loaded += OnScrollBarLoaded;
}
}
private static void OnScrollBarLoaded(object sender, RoutedEventArgs e)
{
if (sender is ScrollBar scrollBar)
{
if (scrollBar.Template != null)
{
// I'm not sure, but the `name` in the following method call might be case sensitive.
if (scrollBar.Template.FindName("PART_Track", scrollBar) is Track track)
{
// do work with `track` here
}
}
}
}
}
您将在 XAML 中“附加”行为的位置:
<ScrollBar guiControls:ScrollBarLogBehavior.LogUserAction="True">
<!-- more here -->
</ScrollBar>
注意:此实现完全忽略为 bool
LogUserAction
值
答案 2 :(得分:-1)
重写方法OnApplyTemplate
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
var textBox = Template.FindName("PART_Textbox", this) as TextBox;
}