Binding/Referencing Method to XAML WPF

binding, c#, events, wpf, xaml

Solution

Well you can do that by attaching code behind to your ResourceDictionary. Few simple steps to achieve that are:

- Say ResourceDictionary file name is `CustomResources.xaml`. Add another file in same directory besides your ResourceDictionary with name `CustomResources.xaml.cs`. Create `partial class CustomResources` inheriting from ResourceDictionary.

Declare your handler for MouseEnter and code behind is ready.

using System;
using System.Windows;
namespace WpfApplication1
{
    public partial class CustomResources : ResourceDictionary
    {
        public void MouseEnter(object sender, EventArgs e)
        {
            MessageBox.Show("Test");
        }
    }
}

- Now, in XAML set `x:Class` attribute and set handler to `MouseEnter`.

XAML :

<ResourceDictionary
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             x:Class="WpfApplication1.CustomResources"
             xmlns:local="clr-namespace:WpfApplication1">
    <ControlTemplate x:Key="TitledWindowControlTemplateKey" 
                     x:Name="PART_ControlTemplate"
                     TargetType="{x:Type local:TitleWindow}">
        <Rectangle>
            <Rectangle.Style>
                <Style TargetType="Rectangle">
                    <EventSetter Event="Mouse.MouseEnter" Handler="MouseEnter"/>
                </Style>
            </Rectangle.Style>
        </Rectangle>
    </ControlTemplate>    
</ResourceDictionary>

Problem

I have this xaml ``` <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:l="clr-namespace:My.Windows" > <ObjectDataProvider x:Key="TitledWindow_Test" MethodName="Test" ObjectInstance={x:Type l:TitledWindow}"> <ControlTemplate x:Key="TitledWindowControlTemplateKey" x:Name="PART_ControlTemplate" TargetType="{x:Type l:TitledWindow}" <Rectangle> <Rectangle.Style> <EventSetter Event="Mouse.MouseEnter" Handler="{StaticResource TitledWindow_Test}"> </Rectangle.Style> </Rectangle> </ControlTemplate> </ResourceDictionary> ``` And my c# code: ``` namespace My.Windows { public partial class TitledWindow : Window { public void Test() { MessageBox.Show("Test"); } } } ``` The problem is that i get the following error: Error 1 'ResourceDictionary' root element requires a x:Class attribute to support event handlers in the XAML file. Either remove the event handler for the MouseEnter event, or add a x:Class attribute to the root element.

Original source

Related problems