WPF绑定到资源实例

时间:2012-11-06 14:27:29

标签: wpf binding instance

我在XAML中定义了ContextMenu,我在代码中修改它:

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

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

    public ContextMenu sosEditContextMenu
    {
        get
        {
            return EditContextMenu;
        }
    }

...并像这样绑定它(下面是一个主题文件,其中'FTWin'是我的主窗口的Name,其中定义了sosEditContextMenu属性:

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

......但它不起作用。我尝试了各种各样的事情,但我得到了关于资源未被发现或没有发生任何事情的例外情况。

我正在尝试做什么,如果是的话,我做错了什么? 我不知道是否setting the DataContext of an object could help,但是按代码为所有TextBox设置它不是很好吗?

1 个答案:

答案 0 :(得分: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" });
}