Home > Enterprise >  How to Set Interaction Behavior from Code Behind in WPF?
How to Set Interaction Behavior from Code Behind in WPF?

Time:11-20

I have a behavior for Window as follows

<Window>
    <my:Notify x:Name="Not"/>
    <behaviors:Interaction.Behaviors>
        <behavior:RebuildBehavior Element="{Binding ElementName=Not}" />
    </behaviors:Interaction.Behaviors>
<Window>

now i want to write this code in code behind, so i used this code:

in Notify.cs (Loaded Event):

RebuildBehavior behavior = new RebuildBehavior();
behavior.Element = this;
Interaction.GetBehaviors(this).Add(behavior);

But my app crashes in the last line Interaction.GetBehaviors(this).Add(behavior);

System.Resources.MissingManifestResourceException: 'Could not find the resource "ExceptionStringTable.resources" among the resources "

Did I write the correct code?

UPDATE: I moved codes to window.cs (Loaded event)

RebuildBehavior behavior = new RebuildBehavior();
behavior.Element = Notify.Instance;
Interaction.GetBehaviors(this).Add(behavior);

crash fixed but not working

CodePudding user response:

The following code would be the equivalent of your XAML markup:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        RebuildBehavior behavior = new RebuildBehavior();
        BindingOperations.SetBinding(behavior, RebuildBehavior.ElementProperty, 
            new Binding() { ElementName ="Not" });
        Interaction.GetBehaviors(this).Add(behavior);
    }
}
  • Related