我在某些ResourceDictionary
中定义了数据模板:
<DataTemplate DataType="{x:Type local:SomeType}">
<TextBlock Text="{Binding Text}" />
</DataTemplate>
我需要获取已创建视图的实例(例如动态附加ToolTip
或控制Visibility
)。
我can订阅Loaded
事件,但我想要更多xaml方法,因为数据模板可以重新定义,重复代码隐藏是乏味的。
的伪代码:
<TextBlock This="{Binding View}" />
我怎样才能做到这一点?
我尝试创建附加行为以像这样使用它
<TextBlock local:MyBehavior.View="{Binding View}" />
但可耻的失败:(
public class MyBehavior
{
public static BindingBase GetView(DependencyObject obj) => (BindingBase)obj.GetValue(ViewProperty);
public static void SetView(DependencyObject obj, BindingBase value) => obj.SetValue(ViewProperty, value);
public static readonly DependencyProperty ViewProperty =
DependencyProperty.RegisterAttached("View", typeof(BindingBase), typeof(MyBehavior), new PropertyMetadata(null, (d, e) =>
{
var element = d as FrameworkElement;
if (element == null)
throw new ArgumentException("Only used with FrameworkElement");
element.Loaded += (s, a) => GetView(element). ???; // kek
}));
}