c# - 从 ElementTree 的根传递元素作为 CommandParameter

标签 c# wpf xaml data-binding mvvm

我通过 Google 和 StackOverflow 进行了很多搜索,但没有任何答案可以解决我的问题。

我有两个 Xaml 文件:

MainWindow.xaml

<Window x:Name="mainWindow">
    <Window.DataContext>
        <!-- Instantiate ViewModel of the MainWindow -->
        <vm:MainWindowViewModel x:Name="viewModel"/>
    </Window.DataContext>

    <!-- Create the Menu of the MainWindow -->
    <custom:MainMenu Grid.Row="0"/>

    <ad:DockingManager x:Name="dockingManager">
    <!-- ... -->
</Window>

MainMenu.xaml
<UserControl>
    <Menu>
        <MenuItem Header="{t:Translate MENU_LAYOUT_SAVE}" Command="{Binding SaveLayoutCommand}" CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=Window}}"/>
        <MenuItem Header="{t:Translate MENU_LAYOUT_LOAD}" Command="{Binding LoadLayoutCommand}" CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=Window}}"/>
    </Menu>
</UserControl>

我的问题出现在这里。而不是传递主窗口对象,我想传递 DockingManager x:Name="dockingManager"从主窗口。但是,如果我尝试通过其名称引用该对象,它会失败......

我尝试了以下绑定(bind):
CommandParameter="{Binding ElementName=dockingManager}"
CommandParameter="{Binding ElementName=dockingManager, RelativeSource={RelativeSource AncestorType=Window}}"

那么如何从 xaml 中的 ElementTree 中找到并引用一个对象( dockingManager )。我想避免在代码隐藏中使用额外的代码。

最佳答案

试试 CommandParameter="{Binding ElementName=dockingManager, Path=.}" .

编辑:
以前的答案是行不通的。这是一个可行的想法...

在 Window.xaml 中:

<custom:MainMenu Grid.Row="0" Tag="{Binding ElementName=dockingManager}" />

在 MainMenu.xaml 中:
<UserControl x:Name="UcMainMenu" />
...
    <MenuItem Header="{t:Translate MENU_LAYOUT_SAVE}" Command="{Binding SaveLayoutCommand}" CommandParameter="{Binding ElementName=UcMainMenu, Path=Tag}"/>

关于c# - 从 ElementTree 的根传递元素作为 CommandParameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19052332/

相关文章:

c# - 使用现有的数据库名称验证实现 OWIN?

wpf - WPF 中的自定义模态窗口?

java - C#中 super 关键字的等价物

c# - 你如何计算字符串的像素大小?

wpf - 如何在用户将数据输入字段之前阻止验证?

wpf - 从 MVVM 绑定(bind)到 View 在 Prism 中不起作用

wpf - 在 wpf 中绑定(bind)观察者列表内的属性

c# - 从资源以编程方式设置 WPF 图像

c# - 在 XAML 中使用在 Silverlight 代码中创建的静态对象

c# - 任何 C# SmartDate 转换器,例如 "sun 11"--> 2009-12-06 11 :00:00