检测VisualTree或LogicalTree中的父项是否在WPF控件中发生了更改

时间:2017-01-09 11:29:54

标签: c# wpf

我需要知道VisualTree或LogicalTree中的父级何时更改Control。我需要这个功能,因为无论何时父进行更改,我都需要重新评估控件的窗口类,以便我可以附加Command-和InputBindings。

我有一种肮脏的方式,这意味着我需要附加到每个父元素并检查事件的父更改,但我希望有另一种解决方案。

示例:

我有一个UserControl

    <UserControl x:Class="WpfApplication21.UserControl1">
    <UserControl.CommandBindings>
        <CommandBinding Command="ApplicationCommands.Cut" Executed="SomeHandler"></CommandBinding>
    </UserControl.CommandBindings>
</UserControl>

我有一个包含一个或多个UserControls的窗口

<Window x:Class="WpfApplication21.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication21"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.CommandBindings>
        <CommandBinding Command="ApplicationCommands.New" Executed="SomeHandler"></CommandBinding>
    </Window.CommandBindings>
    <StackPanel>
        <local:UserControl1></local:UserControl1>
        <local:UserControl1></local:UserControl1>
    </StackPanel>
</Window>

虽然在示例中我已经放了相同的命令,但它只在这里显示在示例中。实际上,每个控件都有不同的命令。每个UserControl的命令需要合并到Window的CommandBindings中(对于InputBindings也是如此 - 这里没有显示)。每个UserControl都是一个动态创建ViewModel的插件,因此每个ViewModel都有一个不同的View(该示例仅显示UserControls,但实际上这些是UserControl的派生)。

出于这个原因,我创建了一个附加到由ViewModel(由我创建)实现的CommandProvider的行为,以便在没有代码隐藏的情况下完成。

由于我有很多ViewModel,因此我也需要管理Command- / InputBindings并将它们附加到Window。一个问题是并非每个View都可以获得一个Focus,并且如果它们被聚焦,那么对于UserControl事件,Command / / InputBindings不起作用。

现在有点清楚吗?我现在的情况有点复杂。

1 个答案:

答案 0 :(得分:3)

  

我有一种肮脏的方式,这意味着我需要附加到每个父元素并检查事件的父更改,但我希望有另一种解决方案。

很抱歉让您失望,但没有其他办法,即没有“AnyParentChanged”事件或您可以联系到的事情。

您需要以某种方式遍历所有父元素,并将事件处理程序连接到每个元素的相应事件。无论是这个还是重新考虑你的整个方法。

取决于可视树中的父级“更改”可能不是解决您尝试做的任何事情的最佳方式。