Thursday, January 15, 2009

How to ensure a new instance of a resource is returned every time it is requested

There's a little known attribute named x:Shared for this purpose. It's little known since it doesn't appear in Intellisense for some reason. Add the attribute it to any item in a resource dictionary and set its value to False to ensure each request returns a new instance.

The value of the attribute is True by default. This means that any given resource request always returns the same instance by default.

This code snippet demonstrates its usage:
<Window.Resources>
    <ContextMenu x:Shared="False" x:Key="menu">
        <ContextMenu.Items>
            <MenuItem Header="A Menu Item"/>
        </ContextMenu.Items>
    </ContextMenu>
</Window.Resources>

<StackPanel>
    <Button Content="Button1" ContextMenu="{StaticResource menu}" Click="Btn_Click"/>
    <Button Content="Button2" ContextMenu="{StaticResource menu}" Click="Btn_Click"/>
</StackPanel>
private void Btn_Click(object sender, RoutedEventArgs e)
{
    Button b = (Button)sender;
    MenuItem item = (MenuItem)b.ContextMenu.Items[0];
    item.IsChecked = !item.IsChecked;
}

Visit the MSDN page for more info about this attribute.



0 comments: