0

我在 XAML 中定义了一个 ContextMenu,并在代码中对其进行了修改:

ContextMenu EditContextMenu;
EditContextMenu  = (ContextMenu)this.FindResource("EditContextMenu");
//Modify it here...

然后,我需要ContextMenu使用数据绑定将其设置为 XAML 主题文件中的所有 TextBoxes、DatePickers 等。我尝试向主窗口添加一个属性:

    public ContextMenu sosEditContextMenu
    {
        get
        {
            return EditContextMenu;
        }
    }

...并像这样绑定它(以下来自主题文件,其中“ FTWin”是定义属性Name的主窗口的主题文件sosEditContextMenu):

<Style TargetType="{x:Type TextBox}">
    <Setter Property="ContextMenu" Value="{Binding Source=FTWin, Path=sosEditContextMenu}"/>
</Style>

...但它不起作用。我已经尝试了各种方法,我要么得到关于找不到资源的异常,要么什么也没发生。

我正在尝试做的事情是否可能,如果是,我做错了什么?我不知道设置对象的 DataContext 是否有帮助,但是通过代码为所有 TextBoxes 设置它不是很好,对吧?

4

1 回答 1

2

将您在 xaml 中定义的菜单放在可以从文本框中看到的资源字典中,而不是使用绑定,只需使用 StaticResource 以您的样式链接它。

<Window x:Class="ContextMenu.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <Window.Resources>

        <!-- The XAML defined context menu, note the x:Key -->
        <ContextMenu x:Key="EditContextMenu">
            <ContextMenu.Items>
                <MenuItem Header="test"/>
            </ContextMenu.Items>
        </ContextMenu>

        <!-- This sets the context menu on all text boxes for this window .-->
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="ContextMenu" Value="{StaticResource EditContextMenu}"/>
        </Style>        
    </Window.Resources>

    <Grid>

        <!-- no context menu needs to be defined here, it's in the sytle.-->
        <TextBox />
    </Grid>
</Window>

您仍然可以通过查找资源在后面的代码中更改它

public MainWindow()
{
    InitializeComponent();

    System.Windows.Controls.ContextMenu editContextMenu = (System.Windows.Controls.ContextMenu)FindResource("EditContextMenu");
    editContextMenu.Items.Add(new MenuItem() { Header = "new item" });
}
于 2012-11-06T15:10:26.383 回答