Get instance of view created by data template

2019-08-07 10:23发布

I have data templates defined in some ResourceDictionary:

<DataTemplate DataType="{x:Type local:SomeType}">
    <TextBlock Text="{Binding Text}" />
</DataTemplate>

I need to get instance of created view (e.g. to attach ToolTip dynamically or control Visibility).

I can subscribe to Loaded event, but I'd like more xaml approach to this, because data templates can be redefined and repeating code-behind is tedious.

Pseudo-code:

<TextBlock This="{Binding View}" />

How can I achieve this?


I tried to create attached behavior to use it like this

<TextBlock local:MyBehavior.View="{Binding View}" />

but shamefully fail :(

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
        }));
}

标签: c# wpf mvvm
0条回答
登录 后发表回答