我需要知道VisualTree或LogicalTree中的父级更改控件的时间。我需要这个功能,因为任何时候,一个父母的变化,我需要重新评估控件的窗口类,以便我可以附加Command-和InputBindings。检测VisualTree或LogicalTree中的父项是否已在WPF控件中更改
我有一个肮脏的方式,这意味着我需要附加到每个父元素和检查事件的父变化,但我希望有另一种解决方案。
实施例:
我有一个用户控件
<UserControl x:Class="WpfApplication21.UserControl1">
<UserControl.CommandBindings>
<CommandBinding Command="ApplicationCommands.Cut" Executed="SomeHandler"></CommandBinding>
</UserControl.CommandBindings>
</UserControl>
和我有一个包含一个窗口或许多用户控件
<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的命令需要合并到窗口的CommandBindings中(对于InputBindings也是如此 - 此处未显示)。每个UserControl都是一个从ViewModel动态创建的插件,因此每个ViewModel都有一个不同的View(该示例仅显示UserControls,但实际上这些是来自UserControl的派生)。
因此,我创建了一个附加到由ViewModel(由我创建)实现的CommandProvider的行为,以便它在没有代码隐藏的情况下完成。
由于我有很多ViewModels,因此也需要管理Command-/InputBindings并将它们附加到窗口。一个问题是,并非每个视图都可以获得焦点,而对于UserControl事件,如果它们被聚焦,Command-/InputBindings不起作用。
现在有点清楚了吗?我现在的情况有点复杂。
没有内置的方式,因为这通常不是必需的(所需的)功能。您需要它,因为您违反了单一责任规则。最好的方法可能是重新设计更简单的东西。 –
@HenkHolterman我不能清楚地明白这个问题,你能解释一下吗? btw @ O. R. Mapper im不是downvoter – WPFUser
“我需要知道VisualTree或LogicalTree中的某个父级更改控件的时间。”我不能得到这个。 – WPFUser