开发者

Is there a way to bind a command to the collapsed event of all TreeViewItems in a treeview?

开发者 https://www.devze.com 2023-01-14 11:07 出处:网络
I am trying to do something similar to what the person in this question wanted to do. Is there any, more elegant, way to do this than the work-around suggested there?

I am trying to do something similar to what the person in this question wanted to do.

Is there any, more elegant, way to do this than the work-around suggested there?

(As a last resort) Is there a different mvvm framework that would have better support for doing this?

Right now I'm trying to make a custom control that inherits from the treeview, like this:

public ModdedTreeView()
    {
        this.AddHandler(TreeViewItem.CollapsedEvent, new RoutedEventHandler(ItemCollapsed));
    }

public RelayCommand<RoutedEventArgs> ItemCollapsedCommand
    {
        get { return (RelayCommand<RoutedEventArgs>)GetValue(ItemCollapsedCommandProperty); }
        set { SetValue(ItemCollapsedCommandProperty, value); }
    }

    // Using a DependencyProperty as the backing store for ItemCollapsedCommand.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ItemCollapsedCommandProperty =
        DependencyProp开发者_Python百科erty.Register("ItemCollapsedCommand", typeof(RelayCommand<RoutedEventArgs>), typeof(ModdedTreeView), new UIPropertyMetadata(null));

protected void ItemCollapsed(object sender, RoutedEventArgs e)
    {
        if (ItemCollapsedCommand != null)
            ItemCollapsedCommand.Execute(e);
    }

I would then bind the command I want to fire, to the ItemCollapsedCommand dependancy property. However even this is not working.

I keep getting an InvalidOperationException: "Dispatcher processing has been suspended, but messages are still being processed."

Any ideas?


I haven't used the "EventToCommand" class described in the link you referenced. But try the one in this post: http://sachabarber.net/?p=514. I just wrote a little sample using the CommandBehavior class in that post and I was able to attach a command to the IsCollapsed event of the TreeViewItem with the following XAML:

<TreeView>
    <TreeView.ItemContainerStyle>
        <Style TargetType="TreeViewItem">
            <Setter Property="local:CommandBehavior.TheCommandToRun" Value="{Binding MyCommand}"/>
            <Setter Property="local:CommandBehavior.RoutedEventName" Value="Collapsed"/>
        </Style>
    </TreeView.ItemContainerStyle>

    <TreeViewItem Header="Item">
        <TreeViewItem Header="Item">
            <TreeViewItem Header="Item"/>
        </TreeViewItem>
    </TreeViewItem>
</TreeView>
0

精彩评论

暂无评论...
验证码 换一张
取 消