[英]How can I attach a property to a control or use a binding that updates whenever VisualTreeHelper.GetParent() changes?
I have a Button
for which I need to detect if it goes into the ToolBarOverflowPanel. 我有一个
Button
,需要检测它是否进入ToolBarOverflowPanel中。
Current Code: 当前代码:
(Logic: Monitor Children.Count
for AncestorType ToolBarPanel
, send to converter and if the value( ToolBarPanel.Children.Count
) = FallbackValue
then ToolBarPanel
probably didn't register as an Ancestor since the Button
is now in ToolBarOverflowPanel
instead) (逻辑:监视
Children.Count
以获取AncestorType ToolBarPanel
,发送到转换器,如果value( ToolBarPanel.Children.Count
)= FallbackValue
则ToolBarPanel
可能未注册为祖先,因为Button
现在位于ToolBarOverflowPanel
public class IsInOverflowPanel : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value?.ToString().Equals("-1");
}
/*ConvertBack(...) not included here*/
}
and XAML: 和XAML:
<ControlTemplate.Resources>
<local:IsInOverflowPanel x:Key="MyOverflowDetector"/>
</ControlTemplate.Resources>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding Children.Count, Converter={StaticResource MyOverflowDetector}, RelativeSource={RelativeSource AncestorType=ToolBarPanel}, FallbackValue=-1}" Value="True">
<!--Do Stuff Here-->
</DataTrigger>
</ControlTemplate.Triggers>
The problem with this code is that it doesn't update when the button goes into the ToolBarOverflowPanel
. 此代码的问题在于,当按钮进入
ToolBarOverflowPanel
时,它不会更新。
But it works at first. 但是起初它是有效的。 My conclusion is that
Children.Count
isn't giving update notifications. 我的结论是
Children.Count
没有给出更新通知。 Is there a way to fix it? 有办法解决吗?
How can I force the converter to update? 如何强制转换器更新? What kind of binding do I need to make it happen?
我需要什么样的约束力才能实现?
Try this for the binding: 尝试进行绑定:
<ControlTemplate.Resources>
<local:IsOverflowPanelConverter x:Key="IsOverflowPanel" />
</ControlTemplate.Resources>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ToolBarOverflowPanel}}, Converter={StaticResource IsOverflowPanel}}" Value="True">
</DataTrigger>
</ControlTemplate.Triggers>
and this converter 这个转换器
public class IsOverflowPanelConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value?.GetType() == typeof(ToolBarOverflowPanel);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
I haven't tested it, so let me know if there are any problems. 我还没有测试过,所以请告诉我是否有任何问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.